Sling Academy
Home/Node.js/Fixing Node.js & Express Error: req.body undefined

Fixing Node.js & Express Error: req.body undefined

Last updated: December 28, 2023

Encountering a req.body undefined error in Node.js with Express can be a common issue usually related to middleware configuration. The req (request) object in Express does not inherently include a body property, we have to use body-parser middleware to populate it. Here are the steps to fix this error:

Install body-parser

First, ensure you have the body-parser middleware installed. It’s bundled with Express.js from version 4.16.0 onwards. In earlier versions, it needs to be installed separately with npm:

npm install body-parser

Use body-parser Middleware

To include body-parser middleware in your application, add the following code to your main server file (usually server.js or app.js):

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

// For Express version 4.16.0 and higher
// included in express by default
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// For express versions lower than 4.16.0
// separate body-parser middleware
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

The express.json() middleware handles JSON content, and express.urlencoded({ extended: true }) handles form submissions.

Other Possible Reasons

If this middleware is correctly installed and you are still receiving the error, check the following:

  1. Make sure the client is sending the request with a Content-Type header, such as Content-Type: application/json for JSON requests.
  2. Verify that the client is sending the data in the body of the request.
  3. Make sure the middleware is placed above any routes that need req.body.

Example Code

Here’s a complete example of an Express server that correctly uses body-parser:

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

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post('/data', (req, res) => {
  if(req.body) {
    res.status(200).send('Data received: ' + JSON.stringify(req.body));
  } else {
    res.status(400).send('No body data received.');
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Now, any POST requests sent to /data endpoint with JSON data in the body will be correctly parsed and accessed through req.body.

Next Article: Node.js & Express Issue: req.body Empty – How to Fix

Previous Article: Fixing Node.js & Express Error: Request Entity Too Large

Series: Dealing with Common Errors in Node.js

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates