Body not being populated in POST request

I'm encountering an issue with transferring data from the client side to the server side.

Within my application, I have a form that needs to be submitted to the server. Since I am utilizing a library to automatically generate my form from a JSON schema file, I must manually submit the form by essentially making a post request with my object. Everything seems to be in order so far, but when my request reaches the backend, it arrives with an empty body.

Client-side post request:

const test = {
    name: "hello"
}
axios.post("http://localhost:8000/my-route/test", test)
    .then(res => console.log("res.data", res.data));

Server route definition:

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(cors());

/* ... */

app.post("/my-route/:type", (req, res) => {
    if (!req.params.type) {
        res.send({
            err: "Please provide type"
        });
    } else {
        console.log('req.body', req.body);

        res.send({
            success: "Generating type " + req.params.type
        });
    }
});

My backend log displays req.body {} rather than req.body { name: "hello" }.

If I opt to JSON.stringify(test), then my log changes to

req.body { '{"name":"hello"}': '' }
, which is not what I had intended.

Answer №1

When making an axios request, ensure that you are sending a JSON payload. If your server is not set up to parse JSON and only handles URL-encoded bodies, you will need to include the following middleware:

app.use(bodyParser.json());

If this parser is missing, the bodyParser.urlencoded(...) middleware will simply populate req.body with an empty 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

Update the value of input within a Struts2 iterator by utilizing JavaScript

As a junior programmer, I am trying to update the value of an input type text within a Struts2 iterator without refreshing the entire page. I believe using JSON could be a solution for this issue. Here is my JSP code: <input type="text" name="cantidad ...

Issue: Encountered a problem when attempting to encode the data type ([object Object]) into a Firestore Value while using Node

While attempting to insert a document with the geopoint dataType in firestore using the following instance: new firebase.firestore.GeoPoint(latitude, longitude) I encountered the following error. https://i.sstatic.net/yKuIs.png ...

What is the process for granting permission for Firebase Functions to access resources on GCP, such as GCE?

I'm facing a challenge in granting permission from my GCP project to a function deployed in Firebase. Here's what I'm trying to accomplish: My site, also deployed in Firebase, calls a backend Firebase Function. The function attempts to acce ...

What is the process for compiled node projects to manage modifications to internal files?

I am currently developing a small program using nodejs that I intend to integrate as a backend service for an expressJS webserver that is still in the works. To prevent displaying the entire program on the webserver itself, I have learned about the possib ...

It seems like KineticJS is removing elements from the canvas that I would prefer to keep

My website features an HTML5 canvas where I showcase a variety of images, text, and shapes using JavaScript functions. The text and shapes are created with the following JavaScript functions: function drawGameElements(){ /* Draw a line for the ' ...

Determine the current whereabouts and actions of the specified user

I am in the process of developing a command for my Discord JS bot that, when activated, will fetch the current game (or status if no game) of the user mentioned in the command. Subsequently, the bot will send a message stating Mentioned User has been playi ...

The CSS styling for a pie chart does not seem to be functioning properly when using jQuery's

https://i.stack.imgur.com/kEAKC.png https://i.stack.imgur.com/03tHg.png After examining the two images above, it appears that the CSS is not functioning properly when I try to append the same HTML code using JavaScript. Below is the snippet of my HTML co ...

Customize Cell Styling with Bootstrap Full Calendar CSS

I am attempting to implement a Bootstrap calendar feature where cells are colored green if the timestamp is greater than today's date. This can be achieved by: $checkTime > $today cell.css = green background I came across this code snippet on St ...

When altering the color of a mesh in Three.js, only a single face is impacted by the modification

I have a GLB model with multiple parts and hierarchy. My goal is to highlight a specific part of the assembly on mouseover. The code snippet I am using for this functionality is as follows: raycaster.setFromCamera( pointer, camera ); ...

Unable to retrieve streaming data within express framework

Here is the code snippet that I have created: router.get('/all-outlets', (_req, res) => { console.log('jererere'); // var sql = knex.select('*').from('retail_outletsss').limit(10); let stream = knex.raw(`sel ...

The directive in an Angular app is not loaded due to lazy loading

Seeking assistance with lazy loading a directive in my Angular application, I am using ui.router and oc.lazyLoad. Below is the code snippet: menu : <ul> <li><a ui-sref="home">Home</a></li> <li><a ui-sre ...

Using URL parameters in Node.js applications

I am encountering an issue with my nodejs setup, and I am hoping someone can assist me. My challenge lies in trying to pass a parameter with a specific value to a page.html file, like this: page.html?s=1 However, I am encountering a problem where the pa ...

Encountering issues with uploading Cloudinary images through Nodejs

I'm having trouble uploading a base64encoded image to Cloudinary using the code snippet below. It's not working as expected and I keep getting a 500 error when making the post request. Can anyone provide me with a solution or suggest what might b ...

Is it a problem with Cucumber Js callbacks or a feature issue?

I would like to create a scenario similar to this: Scenario: initialize new Singleton When an unmatched identity is received for the first time Then create a new tin record And establish a new bronze record And generate a new gold record This s ...

Ways to conceal and reveal an item within a three.js environment

In my scene, I have an object made up of spheres and a hide/show button. The process in my program goes like this: when I choose one of the spheres using raycasting and then press the hide button, that particular sphere becomes hidden. Clicking on the sh ...

Searching for mobile WiFi preferences through a web browserHere are the steps to

Is there a method to access mobile connectivity settings through a website? I am interested in determining the connection type (3G\4G\WiFi) and if it is WiFi, identifying the security method being used. Is this achievable? If so, how? Edit: If ...

Wait for the product details to be fetched before returning the products with a Firestore promise

Although I know similar questions have been asked numerous times before, I am struggling with something that seems quite straightforward to me. We have two tables - one called "order_lines" and the other called "order_lines_meta". My goal is to query the " ...

What is the best way to filter through JSON data in Vue.js?

I'm encountering an issue with my JSON file that I am rendering to a table. I have 11 columns including id, name, and more. I want to search by every column, but the functionality only works for one column. If I try to filter the data multiple times, ...

What is the process of setting up an SSL redirect in NodeJS on an AWS EC2 instance without utilizing either port 80 (http) or port 443 (https)?

I currently have two node servers running on a single host. One server handles HTTP requests and redirects to HTTPS, while the other serves my application: const express = require('express'); const https = require('https'); const http ...

The circular pattern includes six circles perfectly arranged within the larger circle

Can someone help me achieve perfect circular buttons using Bootstrap, CSS, and HTML5? I've tried my best but need some assistance to make them responsive as well. Here is the code I've been working on: <div class="col-md-12"> ...