0

Basically, I am using Thunder Client to send the requests and I am using the post request. The failure that I am facing is that whenever I send the request and also send the body contents and have already used content-type application/json in the header and when at the request portion I try to get req.body it returns undefined. I don't know why this error is occurring. Could someone please help?

const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const Admin = require('../Models/Admin');

//Route 1 : Create an ADMIN Account
router.post('/createadmin', async (req, res)=>{
    
    console.log(req.body)
    res.json(req.body)
       
})

module.exports = router
Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
adil135
  • 1
  • 1

2 Answers2

1

This is a bit late so hopefully you figured it out by now, but you may need to install and then use body parser. So npm i body-parser...then you can use it as necessary demonstrated here:

bguiz
  • 27,371
  • 47
  • 154
  • 243
  • I might be wrong here, but as far as I know Express parses the body as it is, because bodyParser package is already included. However if you want your response to be json you might need to use middleware for that. Some APIs (Stripe for example) require raw body. Here’s a link to express docs about json middleware: https://expressjs.com/en/api.html – Mike K. Apr 10 '22 at 12:13
0

here you just need to install and then use body parser. because to send jason you need a kind of middlevare which is body parser try to use following

//middelevare to pass jason body and put it before routes in your index.js file
app.use(express.json());

following is may smaple code so try to use like this

const connectToMongo = require('./db');
connectToMongo();


const express = require('express');
const app = express();
const port = 3000;


// middelvare to send fake request using thunder client 
app.use(express.json());

//availabel routes
app.use('/app/auth', require('./routes/auth'));
app.use('/app/notes', require('./routes/notes'));
app.get('/', (req,res)=>{
    res.send("hello world");
})

app.listen(port, ()=>{
    console.log("Successfully listening on port no : ", port);
})

I hope it will help you.