我正在使用新的浏览器特性(navigator.sendBeacon)将异步数据发布到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}')发布于 2015-07-11 09:53:57
navigator.sendBeacon POST使用Content-Type:text/plain;charset=UTF-8传输字符串数据。因此,只需添加bodyParser.text()来解析“text/平原”数据:
服务器:
...
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 )发布于 2022-05-05 02:49:34
我们可以通过formData发送数据。
在客户端发送数据:
const formData = new FormData()
formData.append('resource', JSON.stringify({a:'test'}))
const success = navigator.sendBeacon('/api/url', formData)在服务器上以快捷方式接收数据:
对于koa2,我只使用koa2-formidable中间件,只使用/api/url路由器。
https://stackoverflow.com/questions/31355128
复制相似问题