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


i using new browser feature(navigator.sendbeacon) post async data node.js server.

but unable receive on node server. 1 tell me how receive data posted sendbeacon on node server.

node server code is:

var express = require('express'); var app = express(); var bodyparser = require('body-parser');  // set cross origin header 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 request',req.body) });  var server = app.listen(3000, function() {     console.log('express listening http://localhost:3000'); }); 

client side code

navigator.sendbeacon('http://localhost:3000/','{"a":9}') 

navigator.sendbeacon post uses content-type:text/plain;charset=utf-8 transmit string data. add bodyparser.text() parse 'text/plain' data:

server:

... app.use(bodyparser.json()); app.use(bodyparser.text()); ... 

client:

navigator.sendbeacon('http://localhost:3000/', json.stringify({a:9})); 

update

apparently can use blob add content-type:application/json header in request:

client:

var blob= new blob([json.stringify({a:9})], {type : 'application/json; charset=utf-8'}); // blob navigator.sendbeacon('http://localhost:3000/', blob ) 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -