Reputation: 453
When the request from postman initiated with the json as given below, I get hello undefined
as response.
request json
{
"name":"test"
}
my middleware
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.get('/hello', (req, res)=>{
return res.send("hello");
});
app.post('/hello', (req, res)=>{
console.log(req.body);
return res.send(`hello ${req.body.name}`);
})
app.listen(8000, () => console.log('listening on port 8000'));
started the server with following command
npx babel-node src/server.js
Upvotes: 0
Views: 2907
Reputation: 138
use bodyParser as meddleware
const app = express();
app.use(bodyParser.urlencoded({ extended: true })); //add this
app.use(bodyParser.json());
also
app.post('/hello', (req, res)=>{
console.log(req.body);
name.push(req.body.name) // add this if you store in array
return res.send(`hello ${req.body.name}`);
})
Upvotes: 0
Reputation: 453
Actually issue is not with the code. The Postman client making the request didn't mark it as application/json
type request. Once I rectified it, it just worked as expected.
Upvotes: 2
Reputation: 1
Since express 4.16.0 you can use app.use(express.json()); to get the json data from request,in your case it would be.You don't require to use bodyparser and all.
const app = express();
app.use(bodyParser.json()); // remove this
app.use(express.json())// add this line
Upvotes: 3