J
J
Juniorrrrr2022-02-02 21:40:39
Node.js
Juniorrrrr, 2022-02-02 21:40:39

Why does express return an empty req.body?

Please tell me, I raised the server locally / I
use express "^4.17.2"

const express = require('express');
const { v4: uuidv4 } = require('uuid');
const app = express();
const port = 3000;

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

app.post('/api/text', (req, res) => {
  console.log("---", req.body);
  res.send("text");

})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})


I send a POST request via postman, req.body is always an empty object

Please tell me what I'm doing wrong?

61facfe59734f256601316.png
61facff05c8f6457130868.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2022-02-02
@Aleksandr-JS-Developer

Express ^4x comes without body-parser, you need to include it separately

G
grisha228, 2022-02-03
@grisha228

Option N1
Connect body-parser

The code
npm install body-parser
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const app = express();
const port = 3000;
const bodyParser = require('body-parser');

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

app.use(bodyParser.json())

app.post('/api/text',(req, res) => {
    console.log("---", req.body);
    res.send("text");

})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

Option N2
Using chunk.
IMPORTANT. Do the output inside end or remake the code into an asynchronous function and do await for on('data'). In this case, body can only be called inside:
req.on('end', () => {
        console.log("---", body);
    });

otherwise, it will be empty, because body does not have time to write, and on.('end') is executed.

The code
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const app = express();
const port = 3000;

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

app.post('/api/text',(req, res) => {
    let body = '';
    req.on('data', chunk => {
        body += chunk.toString();
    });
    req.on('end', () => {
        console.log("---", body);
    });
    res.send("text");

})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question