Home > Enterprise >  Express.js: undefined request.body
Express.js: undefined request.body

Time:04-10

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

const app = express();
app.use(express.json())
app.use(cors());

app.post('/', (req,res) => {
    console.log(req.body);
    res.send('received')
})

app.listen(5000, console.log('Server is running on port 5000'));

I am trying to send data to the back-end but always getting undefined

enter image description here

I tried to you a parser but seems like just wrapping void into an object

enter image description here

CodePudding user response:

Posting as answer from my comment.

In the second image in postman you need to change the type dropdown from text to JSON, express.json() only parses the body when the header Content-type is set to "application/JSON" and changing that dropdown will automatically include that header.

Here are the docs if it helps explain why you get the empty object in the second image

  • Related