如何接收navigator.sendbeacon"发送的数据在node.js服务器上
How to receive data posted by "navigator.sendbeacon" on node.js server?
我使用新的浏览器功能(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
路由器。
相关文章:
- node.js请求数据事件未在CORS ajax调用中触发
- 在HTML页面上显示node.js服务器中的数据
- AJAX调用并在Node中获取返回数据
- 如何在不重新加载的情况下提交表单,并使用Node+Express将数据传递回同一页面
- 更新从Mysql查询检索到的数据?Node.js节点mysql
- 通过node.js和socket.io向特定用户发送数据
- Node.js-将数据发送到Node.js,并以HTML形式验证插入的数据
- 使用Node/Express随机查询Postgresql表并处理行数据
- Angular JS和Node路由/布线-仅在页面刷新后显示数据
- Node JS,传统的数据结构?(如Set等),任何类似Java.util的node
- 在node.js中用“;“大”;数据
- 如何使用Node.js/MongoDB在AngularJS应用程序中获取特定于目标的数据
- 尝试通过angularjs和node将用户数据发送到mongodb
- node exec()未触发所有数据事件
- Node.js,为事件分配回调函数'数据'
- Node.js输入数据事件停止
- 视频标签仅在移动设备上调用一个字节的数据(Node.js)
- Json 提取和使用数据(node.js)
- Javascript 函数不返回数据 - Node-MySQL
- 麻烦从Firebase数据库获取数据Node.js/JavaScript