Home > Back-end >  req.body undefined with express
req.body undefined with express

Time:02-03

I get a n undefined req.body on my post requests, tried everything, from body-parser through express.json, both together (sure bad) and still cannot get it to work. Any help is really appreciated!!

I have reduced my nodejs server to the minimum:

const app = express();
const bodyParser = require('body-parser');

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

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

app.post('/requests', (req, res) => {
    console.log(req.body);
    res.status(201).json('all ok');
  })

app.listen(4000, () => {console.log('Server listening on port 4000')});

My request is (done with the REST client from VS Code):

POST http://localhost:4000/requests
Content-Type: 'application/json'

{
  "msg":"Some message",
  "other":"Other msg"
}

CodePudding user response:

Im using curl, this one works here even with node 12.22.9, pretty sure you just forgot to declare express on the top or something is wrong with your rest client

curl -X POST http://localhost:4000/requests -H 'Content-Type: application/json' -d '{"msg":"Some message","other":"Other msg"}'

.js

const express = require('express')
const app = express()

const bodyParser = require('body-parser');

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

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

app.post('/requests', (req, res) => {
    console.log(req.body);
    res.status(201).json('all ok');
  })

app.listen(4000, () => {console.log('Server listening on port 4000')});

package.json

{
  "dependencies": {
    "body-parser": "^1.19.1",
    "express": "^4.17.2"
  }
}

CodePudding user response:

Just as info for other lost souls here...

If you use the REST Client app on a windows system, make sure your request has no caps. Im my case:

POST http://localhost:4000/requests/
content-type: application/json

{
  "msg":"Some message",
  "other":"Other msg"
}

AND (Also my mistake): Do not put application/json within any type of quotes, just plain!

(I did do the request from a win and a mac machine, both did not work, but it was that the reason!)

  •  Tags:  
  • Related