Search code examples
javascriptnode.jspostsendbeacon

sendBeacon JSON Data not getting read (serverside) Nodejs and JS


I am trying to send a POST request on visibility change (as described in the docs) and am having limited success. I make the sendBeacon request successfully, but cannot seem to read the object on my Node.js Express server. Here is my Send Beacon js code:

navigator.sendBeacon("/delete-room", JSON.stringify({roomID: 'test'}))

Then, when I handle it through express:

app.post('/delete-room', (req, res)=>{
    console.log('Recieved ' + req.body)
    res.status(200).end()
})

I get this log: Recieved [object Object]. I can't read req.body.roomID, even after parsing the body (which returns the error cannot parse [object Object]). I also tried encoding it in a form:

var formData = new FormData()
formData.append('roomID', 'test')
            
navigator.sendBeacon("/delete-room", data);

Which returns this log on the server: Recieved {}.

Why can't I receive this request? Thanks!


Solution

  • With your code

    var formData = new FormData()
    formData.append('roomID', 'test')       
    navigator.sendBeacon("/delete-room", data);
    

    the sendBeacon() function send data in a raw format via HTTP POST request.

    Install body-parser express middleware (npm install body-parser --save) then:

    // index.js
    const express = require('express');
    const bodyParser = require('body-parser');
    
    const app = express();
    app.use(bodyParser.raw());
    
    app.post('/delete-room', (req, res)=>{
        console.log('Received ' + req.body)
        res.status(200).end()
    })
    
    app.listen(8080, () => console.log(`Started server at http://localhost:8080!`));