Express server consistently receives JSON requests that contain no data in the request body

Currently, I am in the process of developing a small server and website using Express. At this point, my goal is to send a POST request to my Express server with basic credentials encoded as JSON.

The issue I am facing is that no matter what I attempt, the request body always ends up empty on the server side. While on the frontend side, I can verify that the values are present. My code successfully logs the correct username and password before sending the request. Additionally, when inspecting the network panel in Chrome dev tools, I can see the accurate payload being sent to the server.

Frontend code:

<script>

    const username_input = document.getElementById('username');
    const password_input = document.getElementById('password');
    const submit_registration = document.getElementById('submit_registration');
    
    
    submit_registration.addEventListener('click', (event) => {
        const username = username_input.value;
        const password = password_input.value;
        console.log(username, password);
        
        fetch('/register', {
            method: 'POST',
            header: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                'username': username,
                'password': password
            })
        })
        .then(raw_response => raw_response.json())
        .then(response => console.log(response))
        .catch(err => console.log(err))
        
    });
</script>

I also attempted to curl a straightforward POST request to my server. The curl command used:

curl -H POST "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/register

Surprisingly, even with the curl request, the request body in my server code came out empty. I suspect that the problem lies within the backend, although I remain uncertain. To confirm, I implemented requests using both curl and fetch methods.

Below is the Express code snippet for handling POST requests:

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

app.post('/register', (req, res) => {

    console.log(req.body);
    res.status(200).send('Ok');

});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
});

The outcome constantly displays empty curly brackets in the result, whereas there should be a username and password included as shown in the previous requests. It's perplexing why it remains empty despite utilizing Express version 4.17 which supports express.json().

Additionally, I want to mention that previously when I employed an html form and encoded the data using application/x-www-form-urlencoded along with decoding it in my Express app with

app.use(express.urlencoded({ extended: true}))

it was successful. I received the username and password without any issues. However, now with JSON, the body arrives empty on the backend.

This situation has left me feeling quite frustrated.

Answer №1

Modify your fetch request by replacing the header attribute with headers.

Answer №2

Attempt using res.status(200).json('Ok');

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

Can you explain the different types of dynamic page props available in a Next.js application?

Is there a specific type available in Next.js 14 that I can use to replace the "any" type in the TypeScript code snippet below, for my dynamic route? export default async function DetailProduct({ params }: any) { const { imageAddress, title, price } = ...

Unable to set background-image on Node (Limited to displaying only images sourced from Flickr)

I am experiencing difficulty with the background-image node property not functioning properly. In order to test this issue, I am using the "Images & breadthfirst layout" demo as an example (accessible at https://gist.github.com/maxkfranz/aedff159b0df0 ...

Advice for resolving problems with npm path and installation

I have recently switched my nodejs installation to the D:\ drive instead of the C drive and updated the environment variables accordingly for the node & npm folders. After that, I modified the npm installation path by setting "prefix=D:\node&bso ...

Is there a way to retrieve the complete result set prior to calling res.render in Express?

Even though the code is functioning and the page is displaying, a slew of errors appears. Only the first row of data from the dataset is logged to the console before the res.render function is triggered. Error: Can't set headers after they are sent. ...

Speed up the process of distributing files to clients using Node.js Express

In my opinion, Node.js Express is the most efficient and speediest method to create a rapid web application for prototyping. With just a few lines of code and some HTML/JS files, you can have a functional web app up and running in no time. However, one iss ...

Transform the jQuery each method into vanilla JavaScript

I have a script that displays a dropdown in a select box. The current script I am using is as follows: jQuery.each( dslr, function( index, dslrgp) { var aslrp= dslrgp.aslrp; jQuery.each( aslrp, function(index2, pslrp) { var found = 0; ...

How to Delete Elements from an ngList Array in Angular

I encountered an issue while utilizing ngList in a text box to exchange data with my server. The problem arises when I attempt to delete items from the generated array directly, as it does not reflect the changes in the input field. The main concern is th ...

Struggling to accurately determine the intersection face vertex positions in Three.js

Hello there! I've been immersed in the world of three.js, dealing with loading models using THREE.JSONLoader. Currently, I'm faced with the task of selecting these objects and their faces, which I've managed to do successfully. Now, my goal ...

Setting up server-side CORS in ExpressJS will not include the "Access-Control-Allow-Origin" header

Looking to tackle a CORS request for an ExpressJS server, which is new territory for me. Despite encountering similar issues in the past, I can't seem to pinpoint the problem this time around. It appears that the required headers may not be in the cor ...

Organizing objects into arrays in Node.js

I have an array and I need to concatenate an object after the array. Here is my array: const users = [ {name: "Joe", age: 22}, {name: "Kevin", age: 24}, {name: "Peter", age: 21} ] And here is my object: ...

The error message "POST .../wp-admin/admin-ajax.php net::ERR_CONNECTION_CLOSED" appears when a WordPress AJAX request receives data that exceeds 1MB in size

When I attempt to submit a jquery ajax form from the frontend and upload a blob (a variable of string) as a .txt file to WordPress using wp_handle_upload(), everything works smoothly until the file size reaches around 1mb. At that point, an error is displa ...

Got a not-a-number (NaN) value for the `children` prop in a

Just starting out with React and working on a type racer app. I've encountered an issue while trying to calculate WPM (Words per minute) - the calculation keeps returning 'NaN'. I've double-checked all the variables and ensured there ar ...

Visualizing Data with d3.js Force Chart: Integrating Images with Nodes for Dynamic Animation

After enhancing a force diagram to compare two profiles, I am faced with the challenge of getting the main node to display an image. View comparison here How can I centrally align and size the image correctly while making the thumbnail data from the JSO ...

Difficulty capturing emitted events from child components in Vue.js2

Currently, I'm working on developing a Bootstrap tabs component using Vuejs. The tabs component is divided into two parts - the parent tabs-list component that contains multiple tab-list-item components. Take a look at the code for both these componen ...

When attempting to dispatch in getServerSideProps, the State refuses to change. Could it be due to the Redux-Next-Wrapper?

I'm facing an issue where the Redux Store does not change when I dispatch in getServerSideProps. Even though I can see the changes in console log after dispatch, the store appears as an empty array when the page loads. Why are these changes not taking ...

displaying li tag depending on the index value within angularjs

I have an HTML structure similar to the following: <div class="main"> <ul> <li ng-repeat='save in saves'> <h3>{{save.name}}</h3> <div > <ul> ...

Updating a boolean value from true to false within a Vue component while making an Axios API request

My Vue.js and Axios setup involves making an API call, where I aim to temporarily change the value of a variable from false to true using SetTimeout. However, there seems to be an issue with Vue not responding unless the variable name is hard coded. Withi ...

Searching for and replacing anchor tag links within a td element can be achieved using PHP

I am currently customizing my WordPress website and I need to update the URL (product link) of the "product-image" on the "cart" page. I have the following dynamic code: <td class="product-name" data-title="Product"> <a href=&q ...

What's the best way to make a toast notification appear when an API call is either successful or encounters

Seeking guidance on incorporating toast messages within an Angular + Ionic 6 application... My goal is to display a toast message in response to events such as clearing a cart or submitting an order, with the message originating from an API call. While a ...

Schema Connections in Kendo Diagram

I am currently experimenting with the Telerik Kendo diagram in an attempt to create a visual representation. Due to the fact that I am retrieving all shapes and their connections from my database, I encountered an issue where the attributes of my data sour ...