Javascript 如何接收“发布的数据”;导航器.sendbeacon“;在node.js服务器上?

Javascript 如何接收“发布的数据”;导航器.sendbeacon“;在node.js服务器上?,javascript,node.js,Javascript,Node.js,我正在使用new browser feature()将异步数据发布到node.js服务器 但我无法在节点服务器上接收它。所以,有谁能告诉我如何在节点服务器上接收sendBeacon发布的数据吗 节点服务器代码为: var express = require('express'); var app = express(); var bodyParser = require('body-parser'); // set cross origin header to allow cross-orig

我正在使用new browser feature()将异步数据发布到node.js服务器

但我无法在节点服务器上接收它。所以,有谁能告诉我如何在节点服务器上接收sendBeacon发布的数据吗

节点服务器代码为:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// set cross origin header to allow cross-origin request.
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use(bodyParser.json());

app.post('/',function(req,res){
    console.log('i got the request',req.body)
});

var server = app.listen(3000, function() {
    console.log('Express is listening to http://localhost:3000');
});
客户端代码

navigator.sendBeacon('http://localhost:3000/','{"a":9}')

navigator.sendBeacon
POST使用
内容类型:text/plain;charset=UTF-8
传输字符串数据。因此,只需添加
bodyParser.text()
即可解析“text/plain”数据:

服务器:

...
app.use(bodyParser.json());
app.use(bodyParser.text());
...
客户:

navigator.sendBeacon('http://localhost:3000/', JSON.stringify({a:9}));
var blob= new Blob([JSON.stringify({a:9})], {type : 'application/json; charset=UTF-8'}); // the blob
navigator.sendBeacon('http://localhost:3000/', blob )
更新 显然,您可以使用在请求中添加
内容类型:application/json
头:

客户:

navigator.sendBeacon('http://localhost:3000/', JSON.stringify({a:9}));
var blob= new Blob([JSON.stringify({a:9})], {type : 'application/json; charset=UTF-8'}); // the blob
navigator.sendBeacon('http://localhost:3000/', blob )

请发布您的节点服务器代码。@hassansin也添加了服务器代码
application/x-www-form-urlencoded
multipart/form data
,和
text/plain
是sendBeacon内容类型现在唯一允许的值-对于更新版本的express,请使用
app.use(express.text())
。谢谢:)