Search code examples
javascriptnode.jsbeacon

Error 404 when using navigator.sendBeacon to log out a user


hi In my application if the user closes the tab/window I would like to log him out. For this purpose I use navigator.sendBeacon in the following way:

client.js:

window.addEventListener('unload', logData, false);
function logData() {
    var b = localStorage.localStor;
    if (b != null && b != "{}") {
        console.log("closed");
        console.log(JSON.parse(b).email); //prints user email
        navigator.sendBeacon("/log", { email: JSON.parse(b).email });
        localStorage.clear();
    }
}

server.js: (node.js)

var http = require('http');
var url = require('url');
var fs = require('fs');

var server = http.createServer(function (request, response) {

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
    var url_parts = url.parse(request.url);
    var path = url_parts.path;
    var postBody = [];  //for post uses
    if (path === "/log") {
        console.log("looging out"); // doesn't appear in node.js commad line
        postBody = [];
        request.on('data', (chunk) => {
            postBody.push(chunk);
        }).on('end', () => {
            postBody = Buffer.concat(postBody).toString();
            var parsedData = JSON.parse(postBody);
            var emailIndex = usersList.findIndex(function (element) {
                return element.email === parsedData.email;
            });
            console.log("length before :" + usersList.length); //nothing appear
            usersList.splice(emailIndex, 1);
            console.log("length before :" + usersList.length); //nothing appear

        });
    }

In the app I display the number of current connected users using settimeout every 30 seconds the length of usersList ,but when closing the window the localStorage is indeed clear but the user is still connected because the number of connected users doesn't change . It clearly appears that somehow sendBeacon does not go to the server or it goes but does not apply the condition if (path === "/log"). Also after closing the tab I get the following error in the termenal (I work in Visual Code):

"POST /log" Error (404): "Not found"

I searched about how to use sendbeacon and I used it as in here, but I think that the request does not go to the server because of the error I get.

Any idea how to fix this?

Thanks in advance!


Solution

  • Every thing is right but sendBeacon should be like this:

    navigator.sendBeacon("http://localhost:8080/log", { email: JSON.parse(b).email });