I am implementing the MERN stack for a project, and have this code running in an Express server
import express from "express";
import { PORT, mongoDBURL } from "./config.js";
import mongoose from "mongoose";
import { Partner } from "./models/partnerModel.js";
import bodyParser from "body-parser"
const app = express();
app.use(bodyParser.json())
app.post('/community-partners', async (request, response) => {
try {
if (
!request.body.name ||
!request.body.skill ||
!request.body.partnerYear
) {
console.log('req body was', request.body)
console.log('req params were', request.params)
console.log('req query was', request.query)
return response.status(400).send({
message: "Send all required fields!"
});
}
const newPartner = {
name: request.body.name,
skill: request.body.skill,
partnerYear: request.body.partnerYear,
};
const partner = await Partner.create(newPartner);
return response.status(201).send(partner);
} catch(error) {
console.log(error.message);
response.status(500).send({ message: error.message });
}
});
and I am using Postman to send a POST request to http://localhost:5555/community-partners, and when I send:
{
"name": "IBM",
"skill": "IT",
"partnerYear": 2006
}
(with raw selected, JSON format in Postman)
it returns "Send all required fields!", and logs just return empty "{}"
I changed it to return the fields that were sent and it just sends "undefined" for each request.body.name(.skill or .partnerYear too)
If I print (or JSON.stringify) the body, params, or query it all returns empty brackets.
2
Answers
I have done some modification to handle the parsing explicitly and see if it resolves the issue. I’ve used destructuring to extract name, skill, and partnerYear directly from request.body. This can help avoid any potential issues related to accessing properties directly on an undefined object.
I had a similar problem, and adding in the body parser and npm installing fixed it for me!
Here is my code.
And then please check this image.