使用navigator.sendBeacon注销用户时出错404

时间:2017-09-09 09:56:29

标签: javascript node.js beacon

hi在我的应用程序中,如果用户关闭选项卡/窗口,我想将其注销。为此,我以下列方式使用navigator.sendBeacon

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

        });
    }

在应用程序中,我每隔30秒使用settimeout显示usersList长度的当前连接用户数,但关闭窗口时,localStorage确实清晰但用户仍然连接,因为连接用户数量不会改变。很明显,sendBeacon不会以某种方式进入服务器,但它不会应用条件if (path === "/log")。关闭选项卡后,我在termenal中得到以下错误(我在Visual Code中工作):

  

" POST / log"错误(404):"未找到"

我搜索了如何使用sendbeacon,我在here中使用了它,但我认为由于我得到错误,请求不会发送到服务器。

知道如何解决这个问题吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

每件事情都是对的,但sendBeacon应该是这样的:

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