Reshan Kumarasingam
Reshan Kumarasingam

Reputation: 453

POST request returns undefined

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

Answers (3)

Arun AL
Arun AL

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

Reshan Kumarasingam
Reshan Kumarasingam

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

Shubham Dixit
Shubham Dixit

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

Related Questions