如何接收node.js服务器上的“navigator.sendbeacon”发布的数据?
我正在使用新的浏览器function( navigator.sendBeacon )将asynchronous数据POST到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使用Content-Type:text/plain;charset=UTF-8
传输string数据。 所以只需添加bodyParser.text()
来parsing“text / plain”数据:
服务器:
... app.use(bodyParser.json()); app.use(bodyParser.text()); ...
客户:
navigator.sendBeacon('http://localhost:3000/', JSON.stringify({a:9}));
更新
显然你可以使用Blob
在你的请求中添加Content-Type:application/json
头:
客户:
var blob= new Blob([JSON.stringify({a:9})], {type : 'application/json; charset=UTF-8'}); // the blob navigator.sendBeacon('http://localhost:3000/', blob )