shin
shin

Reputation: 351

Node.js: Access JSON body of HTTP POST request with express

I'm making an http post request to my express web server sending dummy data as json. It correctly receives the request and can send back a json object, but for some reason it can't manage to access the post request body.

I'm using this code for express:

const express = require('express');
const app = express();
const port = 3000;

app.post('/test', (req, res) => {
  console.log(req.body);
  res.json({"some": "thing"});
});

app.listen(port, () => {
  console.log(`Listening at http://localhost:${port}`)
});

And this is the code of the request:

const req = http.request({
    hostname: '127.0.0.1',
    port: 3000,
    path: '/test',
    method: 'POST',
    json: {
        url: "https://www.nothing.com",
        name: "hello"
    }
}, res => {
    console.log(`statusCode: ${res.statusCode}`)
  
    res.on('data', d => {
      process.stdout.write(d)
    })
  })
  
  req.on('error', error => {
    console.error(error)
  })
  
  req.end()

As you can see I'm running this locally. The client receives a status code 200 and the json {"some": "thing"} sent by the server, but the server gets "undefined" from req.body. I tried using:

headers: {
   'Content-Type': 'application/json'
}
body: JSON.stringify({
            url: "https://www.nothing.com",
            name: "hello"
        })

instead of json directly in the request options, but to no avail. I even tried using app.use(express.json()); as someone suggested.

What is the problem?

Upvotes: 1

Views: 3400

Answers (2)

shin
shin

Reputation: 351

Apparently the way I was doing the post request was not correct, I had to send the body in a separate line with req.write(), like this:

const http = require('http');
const data = JSON.stringify({ //<--- data to send as body
    url: "https://www.nothing.com",
    name: "hello"
});

const req = http.request({
    hostname: '127.0.0.1',
    port: 3000,
    path: '/test',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    }
}, res => {
    console.log(`statusCode: ${res.statusCode}`);
  
    res.on('data', d => {
      process.stdout.write(d);
    })
  })
  
  req.on('error', error => {
    console.error(error);
  })
  req.write(data); //<--- this line
  req.end();

Upvotes: 1

Related Questions