express-note

How to solve POST request req.body is empty?

1
2
3
4
5
6
7
8
9
10
11
12
13
const express = require('express');

const app = express();

app.post('/add', (req, res) =>{
const {a, b} = req.body; // TypeError: Cannot destructure property 'a' of 'req.body' as it is undefined.
const ret = parseInt(a) + parseInt(b);
res.send(`${a} + ${b} = ${ret}`);
});

app.listen(3000, () => {
console.log(`Example app listening at http://localhost:3000`);
});

Install bodyParser to parse body content

  1. npm instll body-parser
  2. Use bodyParser.json and bodyParser.urlencoded as middleware.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    const express = require('express');
    const bodyParser = require('body-parser')

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

    app.post('/add', (req, res) =>{
    const {a, b} = req.body; // now you can get your request data here
    const ret = parseInt(a) + parseInt(b);
    res.send(`${a} + ${b} = ${ret}`);
    });

    app.listen(3000, () => {
    console.log(`Example app listening at http://localhost:3000`);
    });
Author: Whitey
Link: https://www.whitey.me/2020/11/16/express-note/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.