Unable to retrieve the request body with bodyParser

I am currently working on a NextJS React Application. Within my server/index.tsx file, I have the following code:

import next from 'next';
import express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import { parse } from 'url';
import { createServer as createHttpServer } from 'http';
import { ParsedUrlQuery } from 'querystring';

const port = 9000;
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({ dev });

const handleNextRequests = nextApp.getRequestHandler();

/**
 * Setup for Compression
 */
const shouldCompress = (
  req: express.Request,
  res: express.Response
): boolean => {
  // Do not compress responses explicitly requesting no compression
  if (req.headers['x-no-compression']) {
    return false;
  }

  // Use compression filter function
  return compression.filter(req, res);
};

nextApp.prepare().then(() => {
  /**
   * Setting up Express application
   */
  const expressApp = express();

  // Implement compression in Express
  expressApp.use(compression({ filter: shouldCompress }));
  expressApp.use(bodyParser.urlencoded({ extended: true }));
  expressApp.use(bodyParser.json());
  expressApp.use(bodyParser.raw());
  expressApp.use(express.json()); 

  ...

  expressApp.post("/api/client", async (_req: express.Request, _res: express.Response) => {
    
    console.log(_req.body)
    _res.send(_req.body)
  });


  // Redirect all requests to the next request handler
  expressApp.all('*', (req: express.Request, res: express.Response) => {
    return handleNextRequests(req, res);
  });

  createHttpServer(expressApp).listen(port, async (err?: any) => {
    if (err) {
      throw err;
    }
    console.log(`HTTP server listening on port: ${port}`);

  });
});

On the client side, I am making calls like this:

console.log('json: '+JSON.stringify(inputData))
    await fetch('http://localhost:9000/api/client',{
        method: 'POST',
        body: JSON.stringify(inputData)
    }).then(res => res.json());

When I attempt to log JSON.stringify(inputData), the object is correctly converted to a JSON string. However, when I try to log _req.body from the server side, it always displays {}.

Please assist me in identifying what mistake I might be making.

Answer №1

Experiment with configuring JSON in the headers:

await fetch('http://localhost:9000/api/customer',{
    method: 'POST',
    body: JSON.stringify(userData),
    headers: {
         'Content-Type': 'application/json'
    },

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

Checkboxes within Angular's reactive forms are a powerful tool for creating dynamic user

Currently, I am working on a contact form that includes checkboxes for users to select multiple options, with the requirement of selecting at least one box. My challenge lies in figuring out how to pass all the selected checkboxes' data to an API usin ...

Adjusting the timing of a scheduled meeting

Is there a way for me to update the time of a Subject within my service? I'm considering abstracting this function into a service: date: Date; setTime(hours: number, mins: number, secs: number): void { this.date.setHours(hours); this.date.s ...

Is there a method to restrict the scope of identical components appearing multiple times on a single page in Angular 7?

I have a scenario where I need to place multiple instances of the same component on a page, but when one of them receives input and refreshes, all other components also refresh. Is there a way to prevent this from happening? <tr *ngFor="let map of imgs ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

Transmit data in the form of a buffer

const response = await client.render(data); const Writable = require('stream').Writable; var buffer = []; const myWritableStream = new Writable({ write(chunk, encoding, callback) { ...

The process of setting permissions for a webview app to only access a middleware in next.js

Is there a way to restrict access to middleware in Next.js so that only mobile devices can access it? I need to handle certain DOM elements for a webview app, but for desktop web, I want them to go directly to the index page without passing through the mid ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

How can we utilize Typescript to check if the intern 4 page has finished loading?

I've managed to set up a function in intern 4 using TypeScript that waits for the page to load. However, there are instances where it doesn't work and throws a TimeOutError even when I catch the error within the function. Can someone please take ...

The MDX blog was set up to showcase markdown content by simply displaying it without rendering, thanks to the utilization of the MDXProvider from @mdx-js/react within Next JS

I'm currently in the process of setting up a blog using MDX and Next.js, but I've encountered an issue with rendering Markdown content. The blog post seems to only display the markdown content as plain text instead of rendering it properly. If y ...

Using TypeScript, the Redux toolkit mutation will be passing the post body as a string instead of JSON

Technology Stack: React TypeScript Redux-Toolkit JavaScript The following code snippet demonstrates how JS is used: Page: const onSubmit = async (values: UserPayload) => { let newValues = { ...values, birthDate: birthDate.toISOString ...

What is the best way to invoke a method in a child component from its parent, before the child component has been rendered?

Within my application, I have a parent component and a child component responsible for adding and updating tiles using a pop-up component. The "Add" button is located in the parent component, while the update functionality is in the child component. When ...

What is the best way to retrieve the subclass name while annotating a parent method?

After creating a method decorator to log information about a class, there is a slight issue that needs addressing. Currently, the decorator logs the name of the abstract parent class instead of the effectively running class. Below is the code for the deco ...

Typescript is throwing an error stating that the type 'Promise<void>' cannot be assigned to the type 'void | Destructor'

The text editor is displaying the following message: Error: Type 'Promise' is not compatible with type 'void | Destructor'. This error occurs when calling checkUserLoggedIn() within the useEffect hook. To resolve this, I tried defin ...

Passport.js implementation in a Next.js application does not persist the user's login state when navigating between routes

I'm currently utilizing passport.js with the local-strategy for authentication in my next.js application. Data store requests and authentication are functioning properly. However, I need access to the req.user in another route to retrieve the users._ ...

I'm experiencing an issue where my express-session is being reset with every new request, leading me to question if this is related to the development environment I am using (REACT + EXPRESS)

UPDATE - I have ruled out a development environment issue as the same problem persists in production. Thank you for taking the time to look into this. I've searched through numerous questions and attempted various solutions with no success. To give ...

When using a RESTful API that stores images in the filesystem, how will the client access the image when sending a GET request?

After creating a RESTful API using Node/Express, I have managed to allow clients to upload photos and audio files which are stored in the filesystem using multer. However, I have not yet figured out how to store these files in the database. The question ...

What is the rationale behind transmitting JSON data within HTML in Next.js's static site generation (

When a webpage is loading, the entire HTML document is sent, whereas in client-side routing, only the JSON file and JS chunk are sent. But why does the HTML file filled with data need to contain JSON data too? Is it really necessary since we already have ...

Customizing the Position of Material UI Select in a Theme Override

I'm trying to customize the position of the dropdown menu for select fields in my theme without having to implement it individually on each select element. Here's what I've attempted: createMuiTheme({ overrides: { MuiSelect: { ...

AmCharts stacked bar chart - dynamically adjust value visibility (adjust transparency) based on user interaction

I recently utilized amcharts to construct a bar chart. The creation of my stacked bar chart was inspired by this specific example. Currently, I am attempting to modify the alpha (or color) of a box when hovering over another element on my webpage, such as ...

What is the method to cancel a server action in Next.js?

Visit the Next.js documentation on server actions The documentation does not provide information on how to abort an action or handle abortions. ...