嗨,在我的应用程序中,如果用户关闭了选项卡/窗口,我想让他退出。为此,我以以下方式使用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中工作)中会得到以下错误:
"POST /log“错误(404):”未找到“
我搜索了如何使用send信标,并使用了它,就像在这里中一样,但是我认为,由于我得到的错误,请求没有发送到服务器。
知道怎么解决这个问题吗?
提前感谢!
发布于 2017-09-09 12:05:57
每件事都是正确的,但sendBeacon应该是这样的:
navigator.sendBeacon("http://localhost:8080/log", { email: JSON.parse(b).email });https://stackoverflow.com/questions/46129393
复制相似问题