4

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!

1 Answer 1

2

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!`));
3
  • Could I use this with JSON bodyparser (what I am already using)?
    – imaginate
    Jan 16, 2021 at 16:07
  • Sure! Just add app.use(bodyParser.json());.
    – Webcoder31
    Jan 16, 2021 at 19:32
  • Thanks so much! Would it work if I also did app.use(bodyParser.raw()); (and app.use(bodyParser.json()))?
    – imaginate
    Jan 16, 2021 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.