Express server unable to process Fetch POST request body

I'm currently developing a React app and I've configured a basic Express API to store user details in the database

    app.post("/register", jsonParser, (req, res) => {
    console.log("body is ", req.body);
    let { username, firstname, lastname, password, role, className } = req.body;
    password = MD5(password);
    console.log(className);
    const query = `INSERT INTO users VALUES ('${username}', '${firstname}', '${lastname}', '${password}', '${role}', '${className}')`;
    conn.query(query, (err, res) => {
        if (err) throw err;
        console.log("Registered Successfully");
    });
});

and I'm making a POST request using the Fetch API

const response = fetch("http://localhost:8000/register", {
                                            method: "POST",
                                            mode: "no-cors",
                                            body: JSON.stringify({
                                                "username": username2,
                                                "firstname": firstname2,
                                                "lastname": lastname2,
                                                "password": password2,
                                                "role": "student",
                                                "className": "A1",
                                            }),
                                        })
                                            .then((response) => {
                                                console.log(response);
                                            })
                                            .catch((err) => {
                                                console.log(err);
                                            });

After sending the fetch request, I'm seeing this on the server terminal

body is  {}

leading to an error in the code

What could be the issue here?

Answer №1

It's uncertain what jsonParser represents, but for the sake of this discussion, let's assume it is the result of express.json().

The middleware relies on the Content-Type request header to decide whether to parse the request body or not.

Given that you are supplying fetch with a string as the request body and not specifying a Content-Type header explicitly, it will assume it is transmitting text/plain data, causing the JSON body parser to overlook it.

It's important to note that you cannot assign a Content-Type header to an unsupported value per the enctype without invoking a preflight process. Additionally, you cannot initiate a preflight in mode: "no-cors" (and you won't be able to access the response in that mode either).


const response = fetch("http://localhost:8000/register", {
    method: "POST",
    headers: {
        "content-type": "application/json"
    },
    body: JSON.stringify({
        "username": username2,
        "firstname": firstname2,
        "lastname": lastname2,
        "password": password2,
        "role": "student",
        "className": "A1",
    })
})

Implement the cors middleware on the server to facilitate the cross-origin request. Ensure that you configure it in a manner that supports preflighted requests.

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

Error encountered while using XLSX.write in angular.js: n.t.match function is not recognized

I've encountered an issue while trying to generate an .xlsx file using the XLSX library. The error message I received is as follows: TypeError: n.t.match is not a function at Ps (xlsx.full.min.js:14) at Jd (xlsx.full.min.js:18) at Sv (xlsx.full.min ...

Modifying elements within a JSON array-generated list

As a beginner in JavaScript, I have encountered an issue with my code. It dynamically creates a list from a JSON array called rolesData and displays the data from "roles" in a list based on a random selection (using document.body.appendChild(createList(rol ...

Attempting to iterate over the array of objects in order to discover a match

I am currently working with an object structure that resembles the one shown in the image linked below. My goal is to compare the inner object properties (such as massing type id) with existing IDs. If there is a match, I want to retrieve the name of that ...

Having trouble updating a specific document in my MongoDB collection

I am facing an issue with my function that reads data from the database. I am trying to change the value of the "hasVoted" field in my Voters model from false to true, but it is not reflecting in the database. Even after setting data.hasVoted = true and c ...

Manipulating strings in Discord.js

if(msg.content.includes("[mid]")) { let str = msg.content let pokeID = str.substring( str.indexOf("[mid]") + 5, str.lastIndexOf("[/mid") //get the unique-code for a pokemon ); msg.channel.send ...

Organizing an ExpressJS application using Mongoose Schemas

Where should my mongoose models be located in the context of an ExpressJS application? I'm trying to avoid putting everything into server.js or app.js. Is there a sample code available for reference? ...

the append function combines existing data with new data

After retrieving data through ajax, I am facing a challenge in displaying it within a UI popup: [{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/1.png"}, {"BadgeImage":"http:\/\/lo ...

Pass a bespoke object back to the GraphQL resolver

In my Node-Express backend server with GraphQL setup, I am working on providing a custom object as output for a GraphQL resolver. The usual Sequelize approach hasn't worked for me in this case, so I'm exploring new methods. const RootQueryType = ...

Utilizing Highcharts for Dynamic Data Loading via AJAX

Just delving into the world of Highcharts and hoping that the issue I'm facing is just a simple oversight on my part. I decided to work off the example provided in the Highcharts live update demo - http://www.highcharts.com/demo/dynamic-update and m ...

Error: The Object #<Object> does not contain a function named 'Schema'

Below is the user model schema that we are using. However, when I try to run it on my localhost, I encounter an error: TypeError: Object # has no method 'Schema' // app/models/user.js // Required modules var neo4j = require('neo4j'); ...

When using phonegap with iOS, HTTP requests consistently return a status of 0 when accessing local files

I've encountered an issue while using Phonegap 3.3.0 on iOS. The HTTP request I'm making always returns 0, regardless of whether the file exists or not! var url = './images/pros/imagefile.png'; var http = new XMLHttpRequest(); http.o ...

Prevent validation on a particular input field with JQuery validator and Bootstrap

Is there a way to use JQuery validator to validate an entire form except for a specific input? Here is an example code snippet showing how this can be done: jQuery.validator.setDefaults({ debug: true, success: "valid" }); ...

When a directive is passed a string with HTML tags, the tags are not displayed/rendered as expected

When it comes to passing a string with HTML content to my Angular directive, I've encountered an issue where the rendered output treats the HTML as text. While researching possible solutions, most of them seem to rely on using ng-bind-html directive, ...

Having trouble with AngularJS $location.path() not redirecting properly?

Why am I unable to redirect to a different URL using $location.path in angular.js? .controller('CheckCtrl', function($scope, $localStorage, $location) { $scope.check = function(){ if($localStorage.hasOwnProperty("accessToken") === t ...

Styling the sub-elements using CSS in JavaScript

Currently, I am dealing with two CSS classes: .dragbox and .removebutton. The .dragbox represents a div, while the .removebutton is a button nested within the div. On my page, there are multiple dynamically generated instances of .dragbox. I am seeking ...

Combining JSON Arrays and Merging Objects with PHP

I have a JSON array with keys for 'id', 'type', and 'answer'. I am combining these keys and storing them in the 'id2' column. However, I am unable to retrieve the value of $answers in the output. Why is that? [{"id" ...

What are some creative ways to design the selected tab?

In my Vue parent component, I have multiple child components. There are several elements that toggle between components by updating the current data. The issue is that I am unsure how to indicate which tab is currently active. I've tried various li ...

Redux state assigns object to another object

I started with an initial state that looks like this: let initialState = { items: [ { name: 'a' }, { name: 'b' } ], otherItems: [] } I am attempting to copy the items array and assign i ...

Prevent mobile users from entering text with Material UI Autocomplete on keyboard

Currently, I am utilizing the Material UI Autocomplete component for multi-select functionality. Although it functions perfectly on desktop, I want to prevent keyboard input on mobile devices and only allow touch selection. Essentially, I do not want the v ...

tips for adding text to an input field after it has been submitted

Is there a way to automatically add text to an input field after the user has entered their information? For example, if a user types "youtube.com" into a search bar, could the input then apply ""? ...