[英]How to receive data posted by "navigator.sendbeacon" on node.js server?
我正在使用新的瀏覽器功能 ( 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}')
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 在服務器中接收數據:
對於 koa2,我只使用koa2-formidable
中間件/api/url
路由器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.