如何接收navigator.sendbeacon"发送的数据在node.js服务器上

How to receive data posted by "navigator.sendbeacon" on node.js server?

本文关键字:数据 node js 服务器 navigator 何接收 sendbeacon quot      更新时间:2023-09-26

我使用新的浏览器功能(navigator.sendBeacon)来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传输字符串数据。所以只需添加bodyParser.text()来解析'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 )

我们可以通过formData发送数据。

在客户端发送数据:

const formData = new FormData()
formData.append('resource', JSON.stringify({a:'test'}))
const success = navigator.sendBeacon('/api/url', formData)

用express接收服务器上的数据:

Express js form data

与koa2,我使用koa2-formidable中间件只有/api/url路由器。