首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用navigator.sendBeacon注销用户时出错404

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

Stack Overflow用户
提问于 2017-09-09 09:56:29
回答 1查看 637关注 0票数 0

嗨,在我的应用程序中,如果用户关闭了选项卡/窗口,我想让他退出。为此,我以以下方式使用navigator.sendBeacon

client.js

代码语言:javascript
复制
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)

代码语言:javascript
复制
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中工作)中会得到以下错误:

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

我搜索了如何使用send信标,并使用了它,就像在这里中一样,但是我认为,由于我得到的错误,请求没有发送到服务器。

知道怎么解决这个问题吗?

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-09 12:05:57

每件事都是正确的,但sendBeacon应该是这样的:

代码语言:javascript
复制
navigator.sendBeacon("http://localhost:8080/log", { email: JSON.parse(b).email });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46129393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档