How to solve POST request req.body is empty?
1 | const express = require('express'); |
Install bodyParser to parse body content
npm instll body-parser
- Use bodyParser.json and bodyParser.urlencoded as middleware.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16const 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`);
});