javascript - 使用 navigator.sendBeacon 注销用户时出现错误 404

标签 javascript node.js beacon

嗨,在我的应用程序中,如果用户关闭选项卡/窗口,我想将他注销。为此,我按以下方式使用 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")。此外,关闭选项卡后,我在终端中收到以下错误(我在视觉代码中工作):

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

我搜索了如何使用 sendbeacon,并按照 here 中的方式使用它。 ,但我认为由于我收到的错误,该请求不会发送到服务器。

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

提前致谢!

最佳答案

一切都正确,但 sendBeacon 应该是这样的:

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

关于javascript - 使用 navigator.sendBeacon 注销用户时出现错误 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46129393/

相关文章:

node.js - Node 应该使用什么环境变量来加载库?

node.js - 在一个 docker 容器中同时启动两个 Node 脚本

android - 应用程序终止后,谷歌附近的 API 后台扫描不起作用

swift - 如何在 MacOS (Swift) 上解析 iBeacon

flutter - beacon_broadcast flutter软件包中的错误代码2是什么意思?

javascript - 如何在 Gatsby 网站中添加 bootstrap js

javascript - WebStorm 自动重新格式化 JS 代码选项 : newline after class declaration - before '{' ?

javascript - Laravel 5.6,如何从一个函数返回两个 View

node.js - 使用 sqs-consumer Nodejs 的 SQS 队列并行处理消息

JavaScript 通过点击设置新的背景颜色