Encountering problem with JSON in the bodyParser function

I've encountered an issue while sending data from my React component using the Fetch API and receiving it as JSON on my Express server. When I try to parse the data using the jsonParser method from bodyParser, I only get back an empty object. Strangely, when I switch to using textParser, the data gets sent without any problems.

Edit: Upon checking the request (req) on the server, it appears that nothing is being received in the body. This anomaly seems to occur only with jsonParser and works fine with textParser.

Fetch:

fetch('./test',{
  method: 'POST',
  body: ["{'name':'Justin'}"]
})
.then((result) => {
      return result.json();
    })
.then((response) => {
      console.log(response);
    })
.catch(function(error){
      //window.location = "./logout";
     console.log(error);
    });

Express:

app.use('/test', jsonParser, (req,res) =>{
   res.json(req.body);
})

Answer №1

If you are looking to submit the object {name: 'Justin'}, here is the code snippet you will need:

fetch('test', {
  method: 'POST',
  body: JSON.stringify({name: 'Justin'}),
  headers: new Headers({
    'Content-Type': 'application/json; charset=utf-8'
  })
})

It's important to note that the body parameter cannot accept an array in this context.


However, if your intention was to send an array, you can achieve that by adjusting the body value like so:

JSON.stringify([{name: 'Justin'}])

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

Tips for increasing the size of a textarea

I'm attempting to extend a textarea by adjusting the margin-top property, but it doesn't seem to be working as intended. Here is the code snippet in question: #sqlcontainerLoggedInPage2 { margin-top: 60px; } <div class="container-fluid" i ...

What is the process of calculating the average of JSON data and looping through it multiple times using Javascript?

I've encountered a JSON data set that has the following structure: { name: "Evelyn", assignment: "SCRUM", difficulty: 3, fun: 4 } And so on. My goal is to calculate the average value of both difficulty and fun for e ...

Adjust the checked state of the checkbox based on the outcome of the promise's data

Whenever the checkbox is clicked and the resolved data in a promise is false, I want the checkbox to remain unchecked. If the data is true, then the checkbox should be checked. I have set up a codesandbox for this purpose. This example utilizes react and ...

Tips on presenting messages to users after clicking the submit button?

I am trying to extract data from a table. I am unsure if my current code is able to retrieve the value from the table. <script> function validateForm() { var x = document.forms["assessmentForm"]["perf_rating11"].value; var y = document.f ...

Middleware not being executed in the Express application

In my application, I am utilizing express router to create routes and applying custom middleware to each route. The goal is for the middleware to only execute when specific URLs are accessed within that particular router. Here is the code snippet: const e ...

Issue with JavaScript causing circles to form around a parent div

I am struggling to position a set of circles around a parent div in my code. I want 6 circles to form a circle around the parent div, but they are not lining up correctly. Can someone help me identify what I'm doing wrong? var div = 360 / 6; var ra ...

Trigger file upload window to open upon clicking a div using jQuery

I utilize (CSS 2.1 and jQuery) to customize file inputs. Everything is working well up until now. Check out this example: File Input Demo If you are using Firefox, everything is functioning properly. However, with Chrome, there seems to be an issue se ...

Strategies for transmitting computed variables from a controller to JavaScript once the computation is complete?

Within my application, I have a button that triggers an action called "method" present in the UserController. This particular action involves executing some specific tasks. def method ***performing necessary calculations and operations*** @my_variable ...

Tips for displaying an HTML page using JavaScript

In my project, I am working with an .html file (File X) that needs to immediately open another .html file (File Y) based on a certain value. Could someone provide guidance on the best way to achieve this using JavaScript? Additionally, I would like the pa ...

The dropdown feature in Bootstrap 5 seems to be malfunctioning in Angular 12

I am facing issues while trying to implement the Bootstrap 5 dropdown in Angular 12. After installing all required packages and adding them to the angular.json file, I still cannot get it to work properly. Even after copying the example directly from the ...

Express API on Node.js fails to read Post request JSON data as null

Currently, I am in the process of developing an application utilizing the Mern stack. One of the recent tasks I have accomplished is sending a POST request from the React frontend to the endpoint using Axios. The snippet provided below showcases the code f ...

Is there a way to confirm that a file has been chosen for uploading prior to form submission, by utilizing the jquery validator?

I have a section on my website where users can upload files. I am trying to implement validation to ensure that a file has been selected before the form is submitted. Currently, I am using the jQuery form validator plugin for handling form validations. Th ...

How can I use D3.js to form a circular group in an organization structure, link it with a circular image, and connect

Is it possible to create a radial grouped circle using d3.js, similar to the image below: I have written some code as shown below. However, I am facing challenges in connecting every circle with a curved line and displaying a tooltip when hovering over a ...

NodeJS tutorial: Extracting blob information from API request

After successfully sending blob data from ReactJS through an API call, I have my Node server listening on the specified port. const audioBlob = new Blob(audioChunks, { type: 'audio/wav'}); let fd = new FormData(); fd.append('audio', au ...

Pass on Redis Pub/Sub messages to a designated client in socket.io through an Express server

Currently, in my express server setup, I am utilizing socket.io and Redis pubsub. The process involves the server subscribing to a Redis message channel and then forwarding any incoming Redis messages to a specific WebSocket client whenever a new message i ...

The issue with the jQuery class change not being triggered in Internet Explorer seems to be isolated, as Chrome and

This little jQuery script I have is supposed to show a fixed navigation menu once the page has been scrolled below 200px, and then change the class on each menu list item to "current" when that section reaches the top of the viewport. The issue is that th ...

Transferring JSON encoded information from a controller to a view via ajax within the CodeIgniter framework

After selecting data from the controller, I want to display it on the view using a Bootstrap template. To achieve this, I need to place the following code in my controller: $data['sidebar']='member/dokter/sidebar_psn'; $data['cont ...

I'm looking to customize my d3.js Bar Graph by changing the color of each bar individually and adding a Scale for them. How can I

I am currently working on constructing a graph that illustrates the data for the Amount of Resources utilized Per Project by creating a bar graph. I am aiming to customize the colors of the bars so that each one has its own unique color. Currently, the col ...

Transforming nested tables into JSON format

I have a table that is dynamically generated and I am looking to convert it into JSON format. Despite trying several methods, I haven't been successful. Can someone help me by providing guidance on how to achieve this using jQuery? For your reference ...

Transform JSON data into a C# object

Despite trying previous solutions for a similar issue, I am still unable to get the desired result. Any assistance would be greatly appreciated. Thank you in advance! :) The error message I am encountering is: System.NullReferenceException: 'Object re ...