I am using new browser feature(navigator.sendBeacon) to POST async data to node.js server.
But i am unable to receive it on node server. So could any one tell me how to receive data posted by sendBeacon on node server.
node server code is:
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'); });
client side code
navigator.sendBeacon('http://localhost:3000/','{"a":9}')
POST request (web browser) var http = new XMLHttpRequest(); var params = "text=stuff"; http. open("POST", "http://someurl.net:8080", true); http. setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.
The navigator. sendBeacon() method asynchronously sends an HTTP POST request containing a small amount of data to a web server. It's intended to be used for sending analytics data to a web server, and avoids some of the problems with legacy techniques for sending analytics, such as the use of XMLHttpRequest .
Methods to send response from server to client are: Using send() function. Using json() function.
Storing your Node. js application's configuration data is quite simple - every object in JavaScript can be easily rendered as JSON, which in turn is just string data that can be sent or saved any way you'd like. The simplest way to do this involves the built-in JSON. parse() and JSON.
navigator.sendBeacon
POST uses Content-Type:text/plain;charset=UTF-8
to transmit string data. So just add bodyParser.text()
to parse 'text/plain' data:
Server:
... app.use(bodyParser.json()); app.use(bodyParser.text()); ...
Client:
navigator.sendBeacon('http://localhost:3000/', JSON.stringify({a:9}));
Apparently you can use Blob
to add Content-Type:application/json
header in your request:
Client:
var blob= new Blob([JSON.stringify({a:9})], {type : 'application/json; charset=UTF-8'}); // the blob navigator.sendBeacon('http://localhost:3000/', blob )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With