如何在node.js服务器上接收由“navigator.sendbeacon”发布的数据?

29

我正在使用新的浏览器功能 (navigator.sendBeacon) 异步向 node.js 服务器发送数据。

但是我无法在 node 服务器上接收它。所以有没有人能告诉我如何在 node 服务器上接收由 sendBeacon 发送的数据。

node 服务器代码如下:

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}')

请发布您的Node服务器代码。 - hassansin
@hassansin已添加了服务器代码。 - coder
2个回答

45

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 )

2
现在,application/x-www-form-urlencodedmultipart/form-datatext/plain是sendBeacon Content-Type的唯一允许值 - https://dev59.com/F1cO5IYBdhLWcg3ww0Vt - Avocado
2
对于较新版本的Express,请使用app.use(express.text()) - e18r

0

我们可以通过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 路由。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接