Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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}') 
like image 997
coder Avatar asked Jul 11 '15 08:07

coder


People also ask

How do I accept a post request in node?

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.

What is navigator sendBeacon?

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 .

Which method is used to send the data from NodeJS server to client?

Methods to send response from server to client are: Using send() function. Using json() function.

How does node js store data on server?

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.


1 Answers

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})); 

Update

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 ) 
like image 165
hassansin Avatar answered Sep 22 '22 09:09

hassansin