Zernst
Zernst

Reputation: 325

Post request from postman seems to not be sending any json data

I am trying to test my project out, and I am using postman right now to pass in some data: I have set postman to "POST" to my local server through "body", and then I send the following:

{
    "name": "My Name"
}

Then, my server file post request is:

const express = require('express'),
router        = express.Router(),
gravatar      = require('gravatar'),
bcrypt        = require('bcryptjs'),
{check, validationResult} = require('express-validator');

// User Model
const User = require('../../models/User');

// @route       GET api/users
// @description Test Route
// @access      Public
router.get('/', (req, res) => {
    res.send("User Route")
});

// @route       POST api/users
// @description Register User
// @access      Public
router.post('/', [
    check('name', 'Name is required').not().isEmpty(),
    check('email', 'Please enter a valid email address').isEmail(),
    check('password', 'Password must contain at least 6 characters').isLength({min: 6})
], async (req, res) => {
    return res.send(req.body);
});

module.exports = router;

I put in the res.send(req.body) to confirm anything is being sent to my server in general before I test any of the other code out, however, the res.send only returns: {} meaning that no json information has been sent to my server. I know that the routes work because when I put in a GET request, it acts as expected. Is there something obvious I am missing here? Thank you.

enter image description here

Upvotes: 0

Views: 4262

Answers (2)

Ahmed El-Beltagy
Ahmed El-Beltagy

Reputation: 99

the Reason for this problem is you need to use Body Parser##


Body-Parser used to process form data or handle JSON payloads in API requests. For instance, when building RESTful APIs, it ensures that the data sent by the client is correctly parsed and ready for processing by backend logic.

the Solution : you should declare the json() function in top of your main file like as index.js

const express = require('express');
const app = express();
app.use(express.json());  //the Solution

app.listen( 3000,()=>{
console.log("Server is Listening on Port 3000");

})

Upvotes: 0

Zernst
Zernst

Reputation: 325

I have figured out the answer to my issue. In the "Headers" I was missing the "Content-type - application/json". After adding this is seems to work.

enter image description here

Upvotes: 2

Related Questions