The body-parser in ExpressJS seems to be malfunctioning as it returns an empty response in a post request

My server creation process involved using express.js, body-parser, and typescript. Here is a snippet of the code:

app.ts

import express, { Application, Request, Response } from 'express';
import morgan from 'morgan';
import bodyParser from 'body-parser';
// import Router from './routes';
import cors from 'cors';

const app: Application = express();

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan('tiny'));
// app.use('/api', Router);
app.post('/test', (req: Request, res: Response) => {
    console.log("req.body => ", req.body)
    res.send(req.body)
})

export default app;

index.ts

import app from './app';
import * as dotenv from 'dotenv';
dotenv.config();

app.listen(process.env.PORT, () => {
  // tslint:disable-next-line: no-console
  console.log(`HTTP Server successfully started at port ${process.env.PORT}`);
});

.env

PORT=8080

package.json

...
"scripts": {
    "start": "node build/index.js",
    "build": "tsc",
    "dev": "cross-env NODE_ENV=development && nodemon",
    ...
},
... 

I made a request using Postman.

// header
Content-Type: application/json

// endpoint
POST http://localhost:8080/test

// body
{
    "title": "Testing",
    "description": "I am testing server."
}

The response from the backend's console was

req.body => {}

Expected result should be

req.body => { "title": "Testing", "description": "I am testing server." }
, but it came out empty.
I spent approximately 2 hours trying to troubleshoot this issue.

Answer №1

I made changes to app.ts and it is now functioning correctly.

import express, { Application, Request, Response } from 'express';
import morgan from 'morgan';
import bodyParser from 'body-parser';
// import Router from './routes';
import multer from 'multer';
import cors from 'cors';

const app: Application = express();
const upload = multer()

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(upload.none()); 
app.use(morgan('tiny'));
// app.use('/api', Router);
app.post('/test', (req: Request, res: Response) => {
    console.log("req.body => ", req.body)
    res.send(req.body)
})

export default app;

I added the multer module for handling form-data successfully.

Answer №2

Express comes with its own built-in parser.json() function. Instead of

bodyparser.josn()

you should try using

express.json()

Also, remember to send the data in Postman by selecting the POST method and utilizing the raw section to send the JSON object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering file uploads using Express in Node.js

Here is a snippet of my code: app.configure(function () { app.use(express.static(__dirname + "/media")); app.use(express.bodyParser({ keepExtensions: true })); }) app.post('/upload', function (req, res) { console.log(r ...

Triggering multiple updates within a single method in Angular will cause the effect or computed function to only be triggered

Upon entering the realm of signals, our team stumbled upon a peculiar issue. Picture a scenario where a component has an effect on a signal which is a public member. In the constructor of the component, certain logic is executed to update the signal value ...

Share a photo through Express and render it using EJS

Currently in the process of developing a quiz application using the MEAN stack. The plan is for my server to transmit an object that includes all the necessary details about each question, including answers, images, and question text. My overarching goal ...

Is it necessary to transmit rule specifics to Stepfunctions?

Is it feasible to achieve what I'm attempting, or am I starting with an impossible task? When a Event Bridge Rule is triggered by an added event pattern, like shown below, should the detailed information be included in the step input? const rule = ne ...

Creating a gradient background with the makeStyles function

Why is it that the background: 'linear-gradient(to right, blue.200, blue.700)' doesn't work within makeStyles? I just want to add a gradient background to the entire area. Do you think <Container className={classes.root}> should be rep ...

Encountering an issue with importing typeDefs in Apollo Server (Typescript) from an external file

I decided to move the typeDefs into a separate file written in typescript and then compiled into another file. Upon doing so, I encountered the following error: node:internal/errors:490 ErrorCaptureStackTrace(err); ^ Error [ERR_MODULE_NOT_FOUND]: Una ...

Issue with the loading of Firebase in Chrome extension's background script is inconsistent

I am currently working on developing a Chrome extension that utilizes Google Firebase for authentication. In my project, I am employing webpack for building purposes, with Firebase being utilized in the background script. However, during the initial initi ...

having trouble accessing information from the .env file in my node.js application

I encountered an issue while trying to access data from my .env file using JavaScript. My file structure is as follows: enter image description here Within the .utils folder, I have a file named mail.js where I am attempting to retrieve port and other in ...

Stop the direct importing of modules in Angular applications

I have a feature module that declares components and also configures routing through a static function. @NgModule({ declarations: FEATURE_COMPONENTS, entryComponents: FEATURE_COMPONENTS, imports: [ UIRouterModule, ... ] }) export class Fea ...

Exploring the features of NodeJS, diving into the world of mapping,

Currently, I am working in a Node.js environment and dealing with an array of IDs. My goal is to filter these IDs based on the response of another API call. Essentially, I need to check if each ID meets certain criteria specified by this external API. Whi ...

Parsing JSON data results in a string output

After realizing that my initial post was not clear enough, here are more details. Jade: meta(name='revObj', content=(JSON.stringify('#{rev[1]}'))) The resulting HTML from Jade: <meta name="revObj" content=""{ companyAddress: &apo ...

Tips for obtaining the "inner type" of a particular "instance" in TypeScript's generics

Unable to find more appropriate language to elaborate beyond the title, I'm going to rely on the code itself: let var1 = someExternalLibraryMethod(); // assume var1 is implicitly Promise<string> let var2: typeof var1; // this approach enables ...

Make sure that the Chai assertion does not result in any errors

One of my functions involves retrieving file content. export function getFileContent(path: string): any { const content = readFileSync(path); return JSON.parse(content.toString()); } If I need to verify that calling getFileContent(meteFile) result ...

What is the best way to showcase an Angular component that has been initialized programmatically?

I currently have the following set up: Users Component HTML: <div class="users"> <ul class="users__list"> <li *ngFor="let user of users"></li> </ul> </div> Users Component TS: impo ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

Deciphering key-value pairs that are separated by commas

I am looking to convert the following format: realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*" Into this JSON object: { realm: "https://api.digitaloce ...

Searching through Mongoose using various fields, some of which are optional

Recently, I've delved into the world of mongoose and am currently working on an app to enhance my learning. My project involves an Artist Schema and a search form with multiple optional fields. For example, users can input a name, minimum age, and sea ...

What is the best way to fetch the chosen item in an Angular select dropdown

I am working on a dropdown that populates with items of type ObjectA. item.component.html: <label>items list: <select formControlName="itemsCtl" (change)="onChange()"> <option *ngFor="let item of itemList" [value]="item">{{i ...

Tips for integrating frontend npm packages into your project

As a beginner in Node.js web development, I recently used ExpressGenerator to create a project with the ExpressJS framework. I'm now looking to integrate the FineUploader front-end JS library into my application, which is available as an NPM package. ...

Server Deployment Fails to Receive Next.JS Cookie

I am in the process of building my own personal website and blog. I have developed a React Frontend using Next.JS, which is deployed on Vercel. Additionally, I have created an Express API as the backend to manage connections to my MongoDB database using Mo ...