Friday 19 May 2017

NodeJS Ajax requests working exactly seven times

I'm currently learning JavaScript / NodeJS / electron, and I want to build a small presenter-app to remotely control powerpoint-presentations.

I've setup a server using electron like this:

const electron = require('electron');
const robot = require("robotjs");
const fs = require('fs');
const express = require('express');
const cors = require('cors');

const {
  app,
  BrowserWindow
} = electron;

var mainWin = null;
var contentString;

app.on('ready', function() {
  mainWin = new BrowserWindow({
    width: 800,
    height: 600
  });

  contentString = "";

  // Remove Menu-Bar
  mainWin.setMenu(null);

  const port = 3000;

  var app = express();
  app.use(cors());

  app.post('/remote/forward', function(request, response, next) {
    var ip = getRemoteIP(request);
    log(mainWin, "presenter - forward");
    robot.keyTap("right");
  });

  app.post('/remote/backward', function(request, response, next) {
    var ip = getRemoteIP(request);
    log(mainWin, "presenter - backward");
    robot.keyTap("left");
  });


  app.listen(port, function() {
    log(mainWin, 'server listening on port ' + port);
  });
});


function log(mainWin, text) {
  contentString += getFormattedDate() + " " + text;
  contentString += "<br />";
  mainWin.loadURL("data:text/html;charset=utf-8," + encodeURI(contentString));
}

I call these with two js-functions:

function sendForwardRequest() {
  $.ajax({
    type: 'POST',
    data: {
         blob: {action:"forward"}
     },
    contentType: "application/json",
    dataType: 'json',
    url: 'http://192.168.2.110:3000/remote/forward',
    success: function(data) {
      console.log('success');
    },
    error: function(error) {
      console.log("some error in fetching the notifications");
    }
  });
}

function sendBackwardRequest() {
  $.ajax({
    type: 'POST',
    data: {
         blob: {action:"backward"}
     },
    contentType: "application/json",
    dataType: 'json',
    url: 'http://192.168.2.110:3000/remote/backward',
    success: function(data) {
      console.log('success');
    },
    error: function(error) {
      console.log("some error in fetching the notifications");
    }
  });
}

I'm sure that this solution is quite miserble, as I said, I'm currently learning this. My question now is: This works for exactly seven times. After that, I have to reload my clients browser. How can I fix this? Also, what would be a better solution for the requests? I'd like to have only one app.post()-method and use the given post-parameters instead. Last question: What could be a nicer method for the logging? I'd like to append content to my window instead of having to reload the whole string each time.

Thank you very much!



via Marcel

No comments:

Post a Comment