2

I have a simple Node.js program running on port 3000 that receives POST requests and logs them:

const express = require('express');
const app = express();
app.post('/post', async (req, res) => {
    console.log('req.body:', req.body);
    console.log('req.rawHeaders:', req.rawHeaders);
});

However, whenenever I send it a POST request:

$ curl --data "param1=value1&param2=value2" http://localhost:3000/post

The request received by the program just contains the headers and is missing the body:

$ node server.js
req.body: undefined
req.rawHeaders: [
  'Host',
  'localhost:3000',
  'User-Agent',
  'curl/7.73.0',
  'Accept',
  '*/*',
  'Content-Length',
  '27',
  'Content-Type',
  'application/x-www-form-urlencoded'
]

What am I doing wrong here? Why is the body of the request always undefined?

Altay_H
  • 489
  • 6
  • 14

1 Answers1

1

I think need to add a little bit more configuration to node.js file, especifically you must add the body-parser dependency so you can extract the entire body portion from the incoming request.

You must install body-parser with npm: npm install body-parser --save

After that you should add it to your file and add configuration:

const bodyParser = require('body-parser')
const express = require('express');
const app = express();

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))

More information on this post: https://stackoverflow.com/questions/38306569/what-does-body-parser-do-with-express#:~:text=body%2Dparser%20extract%20the%20entire,submitted%20using%20HTTP%20POST%20request.

Manuel Duarte
  • 644
  • 4
  • 18
  • 1
    Thanks, that worked! It looks like it can also be done without the additional `require('body-parser')`: https://nodejs.dev/learn/get-http-request-body-data-using-nodejs – Altay_H Nov 07 '20 at 00:19