4

From my client-side I'm doing a fetch with data like this to a webhook on my Firebase node.js server.

const url = 'https://us-central1-<app>.cloudfunctions.net/addUserdata';
const data = {
  firstName: 'John',
  lastName: 'Doe',
  email: 'john.doe@email.com'
}

const request = new Request(url, {
  method: 'POST',
  body: data,
  mode: 'no-cors',
  headers: new Headers()
});

fetch(request)
.then(function(result) {
    console.log(result);
})

I'm just trying to catch the data for now like this.

exports.addUserdata = functions.https.onRequest((req, res) => {
  console.log(req.body);
  res.send(200);
});

Unfortunately my req.body is an empty object. What I'm a missing or doing wrong?

Thore
  • 1,918
  • 2
  • 25
  • 50

2 Answers2

3

Pass JSON, FormData, Blob object or string to body. Request.body does not expect a JavaScript object.

body: JSON.stringify(data)
guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    @Thore See [`Request()`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) at _"Note: The body type can only be a `Blob`, `BufferSource`, `FormData`, `URLSearchParams`, `USVString` or `ReadableStream` type, so for adding a `JSON` object to the payload you need to stringify that object."_, see also [Fetch with ReadableStream](https://stackoverflow.com/q/40939857/) – guest271314 Jul 30 '17 at 18:38
0

On POST requests you have to wait a bit to get data into request.body

    var body = '';
    req.on('data',function(data) { body += data; });
    req.on('end', function(data) {
        req.body = JSON.parse(body);
    });
Jarek Kulikowski
  • 1,399
  • 8
  • 9