Skip to content

Express.Router, body-parser and post request body

I am trying to seperate my routes using express.Router and testing some post requests with Postman. Doing a post request to /test without using router body-parser works fine and i can see the body. Doing the exact same request to /posts which is using Router gives me undefined for the body. I call body-parser middleware before the posts router. Is there something i am missing?

My express server file:

const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
app.post('/test',(req,res)=>{
    console.log('Add post:',req.body);
});
app.listen(3000);

My posts router file:

const express = require('express');
const router = express.Router();
router.get('/',(req,res)=>{
    res.send('Posts');
});
router.post('/',(res,req)=>{
    console.log('Add post:',req.body);
});
module.exports = router;

My postman request with Content-type header set to application/json: img

Answer

As soon as i posted the question i found out what that i wrote req and res in the wrong order. 1 hour and a half for a silly mistake! Have a nide day everyone!