skip to Main Content

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


  1. 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.

    import express from "express";
    import { PORT, mongoDBURL } from "./config.js";
    import mongoose from "mongoose";
    import { Partner } from "./models/partnerModel.js";
    
    const app = express();
    
    app.use(express.json());
    
    app.get('/', (request, response) => {
        console.log(request);
        return response.status(234).send('never working.');
    });
    
    app.post('/community-partners', async (request, response) => {
        try {
            const { name, skill, partnerYear } = request.body;
    
            if (!name || !skill || !partnerYear) {
                return response.status(400).send({
                    message: "Send all required fields!"
                });
            }
    
            const newPartner = {
                name,
                skill,
                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 });
        }
    });
    
    const PORT = 5555;
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
    
    Login or Signup to reply.
  2. I had a similar problem, and adding in the body parser and npm installing fixed it for me!

    Here is my code.

    const express = require("express");
    const bodyParser = require('body-parser'); //add
    const app = express();
    const PORT = 3000;
    
    app.use(bp.json()) //add
    app.use(bodyParser.urlencoded({ extended: true })) //add
    
    app.get('/', (req, res) => {
      res.status(200).send('Hello World')
    })
    
    app.post('/', (req, res) => {
      console.log('req body was', req.body)
      console.log('req params were', req.params)
      console.log('req query was', req.query)
      let textBody = JSON.stringify(req.body); //add
      res.status(200).send('Body received was n' + textBody) //add
    })
    
    app.listen(PORT, ()=> {
      console.log(`listening on port ${PORT}`)
    });
    

    And then please check this image.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search