Sending data from a React client to an Express server using a POST

Currently facing a challenge with sending a post request from React to my Express server backend. The request payload seems to be correctly structured, and I can successfully receive a hardcoded response from the server on the frontend.

However, the issue arises when it appears that the data itself is not reaching the server - calling console.log(req.body) on the server returns undefined. It's a puzzling situation.

Upon inspecting the network tab:

  • The Headers status shows 200, indicating the request completed
  • The Payload displays the JSON object formatted correctly as
    {body: {url: "https://example.com"}}
  • The Response also comes back correctly! {response: "foo"}

This is the API function on the client-side:

const callBackendAPI = async (query) => {
        const response = await axios.post('/', {
            body: { url: query },
        });
    }

Note: Added "proxy": "http://localhost:3001" to the client's package.json file.

On the server side:

const express = require('express');
const app = express();

app.post('/', (req, res) => {
    console.log(req.body); // <------ **Here's the issue, there's nothing here**
    res.json({ response: 'foo' });
    // if I instead send res.json(req.body), the response is empty in the Network tab
});

Answer №1

If you want to handle the incoming request body in Express, you can use the body-parser library:

To install it, use: npm install body-parser

const express = require('express');
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json())

app.post('/', (req, res) => {
    console.log(req.body); // <------ **This is where the issue lies, no data is showing up**
    res.json({ response: 'foo' });
    // However, if I send res.json(req.body), the response shows empty on Network tab
});

Alternatively, starting from version 4.16.0 of Express, express.json() has been re-added according to https://github.com/expressjs/express/releases/tag/4.16.0. This means you can now use express.json() without needing to install body-parser.

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

app.post('/', (req, res) => {
    console.log(req.body); // <------ **This is where the issue lies, no data is showing up**
    res.json({ response: 'foo' });
    // However, if I send res.json(req.body), the response shows empty on Network tab
});

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

Having difficulty accessing the Material UI Icons

I encountered an issue when attempting to utilize Material UI icons - as soon as I added the icon component, an error occurred. https://i.stack.imgur.com/issmm.png For reference, you can find the code on CodeSandbox at the following link: https://codesand ...

I'm wondering, on a storybook, where is the best place to set my MUI X license key

Can you help with where to specify my license key in Storybook? I need guidance on where to set the license key in Storybook. According to MUI Docs, it should be done before React renders the first component and only once in the application. However, I ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

Expanding the size of an array list item in React

I have an array containing various currencies: const currencies =['USD','EUR','AUD','CNY','AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'A ...

Condense items into objects and arrays when the Express query yields multiple objects in a many-to-many query

I have a situation where my SQL queries are returning multiple objects due to a many-to-many mapping in express. I am in search of a tool that can help me simplify these common objects by nesting arrays of objects within them. SELECT * FROM User LEFT JOIN ...

How can I adjust the vertical position of Material-UI Popper element using the popper.js library?

https://i.stack.imgur.com/ZUYa4.png Utilizing a material-ui (v 4.9.5) Popper for a pop-out menu similar to the one shown above has been my recent project. The anchorElement is set as the chosen ListItem on the left side. My goal is to have the Popper alig ...

Ensure that every route is prefixed with /api

Is there a way to set all routes accepted by Express to start with /api without explicitly defining it? Current: this.app.get('/api/endpoint-A', (req, res) => { return res.send('A'); }); this.app.get('/api/endpoint-B', ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

The callbackFinished function is not defined in the winwheel library

Every time I attempt to call a function with the callbackFinished property inside the animation of winwheel, I encounter an error stating that the function is not defined, even though it is defined in the same class. import React from 'react' imp ...

Is it possible to execute JavaScript code (using Node.js) through AppleScript on MAC OS?

After downloading Node.js for MAC OS from this link: http://nodejs.org/download/ (http://nodejs.org/dist/v0.10.29/node-v0.10.29.pkg), I needed to execute a JavaScript on Google Chrome. To do this, I utilized the following AppleScript code: do shell script ...

Using Axios to retrieve data from a MySQL database is a common practice in web development. By integrating Vue

I have developed another Vue.js admin page specifically for "writer" where I can display post data fetched from a MySQL database. The admin page called "admin" is functioning properly and responding with all the necessary data. The following code snippet ...

When the disk space is insufficient, the createWriteStream function will not trigger an error event if the file is not completely written

One challenge I'm encountering involves using createWriteStream: Imagine I have a large 100mb file that I want to write to another file on the disk. The available space on the disk is only 50mb. Here's my code snippet: const fs = require(&a ...

Error: Cannot iterate over Redux props map as it is not a function

I've encountered an issue while trying to render out a Redux state by mapping through an array of objects. Despite receiving the props successfully, I keep getting an error stating that 'map is not a function'. It seems like the mapping func ...

The height of the Material UI Paper component is not appropriately matched with the parent component

I am currently working with the Paper component that contains a Card component, and I am trying to make its height fill the entire screen. To simplify the problem, I have provided the following code: import React from "react"; import { makeStyles ...

The fetch() function is inundating my API with an overwhelming amount of requests

After implementing the following function to retrieve images from my API, I encountered an issue: function getImages() { console.log("Ignite"); fetch('https://api.itseternal.net/eternal/stats', { headers: { & ...

"Encountering difficulties while trying to modify the QuillNoSSRWrapper value within a Reactjs

Currently, I am working on a project involving ReactJS and I have opted to use the Next.js framework. As of now, I am focused on implementing the "update module" (blog update) functionality with the editor component called QuillNoSSRWrapper. The issue I ...

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

What are the steps to deploy a React, Next.js, and Express.js application on Netlify?

I am currently in the process of deploying my application to Netlify, featuring a combination of React, Next.js, and Express.js. While there are no errors showing up in the Netlify console, unfortunately, the site is not live as expected. https://i.stack ...

Encountering an issue with Vue JS axios request and filter: the function this.XX.filter is not operational

I am encountering challenges while trying to implement a basic search feature on a JSON file obtained through an API. Each component works independently: I can successfully retrieve data from the API, perform searches on non-API data, and even search cert ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...