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

When setting up columns in a MUI DataGrid, it's important to remember that each field must have a unique name to avoid any conflicts. Having

I am currently working on a DataGrid project where I aim to display the values of ready_by and name. Here is an image for reference: https://i.stack.imgur.com/3qZGa.png In my code configuration, the setup looks like this: (specifically focusing on the la ...

Troubles encountered when populating the array within a Vue component

I am experiencing an issue with my ProductCard component where the addItem method is not successfully adding a new item to the array. <template> <div class="card"> <div v-for="item in TodoItems" :key="item.id ...

What is the best way to create a delete route for multiple items using Node.js, Express, and MySQL?

Attempting to remove a group of items from the client based on their sku code. import express from 'express'; import { pool } from './mysql'; import cors from 'cors'; import { config } from 'dotenv'; config(); const ...

Is there a way for me to direct to a different HTML page once I click on a certain data point?

At the moment, I have been utilizing this complete set of calendar codes. <!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <link href='fullcalendar.css' rel='stylesheet' /> <link href=&a ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Steps to keep only one submenu open at a time and close others

Struggling to figure out how to open one submenu at a time, and I can't seem to locate the issue! I've searched around for solutions but haven't found anything that works for me. The submenu also needs to remain closed when the page loads. - ...

At times, Node.js GET requests may unexpectedly receive an HTML document instead of the expected JSON data,

I'm using node.js along with discord.js to create a discord bot. Currently, I have implemented a GET request using the npm request module. The code functions properly where if a user types "!cat", it fetches data from and displays a cat picture. How ...

Clicking the submit button in JavaScript will trigger a request to the Spring MVC backend,

When I use the following code, it gives me an object response: @RequestMapping(value = "/NewLogin",method = RequestMethod.POST) public @ResponseBody Token getAllBooks( Token token = new Token(); token.setValue(encryptedMessage); return toke ...

Connecting NodeJS and React for seamless communication with a backend API

Currently, I am running a NodeJs application with Express Framework and React on the frontend. Everything was working perfectly during development when making requests until I added https to the production server. Now, the login functionality using passpor ...

Implementing a method for JQuery event handlers to access variables within a module pattern

var MODULE = (function() { var app = { hi: "hi dad", // How can I retrieve this value? onSubmitClick: function() { $('button').click(function() { console.log(hi); // Is there a way to access ...

Expand the accordion to reveal all the content

I'm facing an issue with my accordion where a scrollbar appears in every content section. To fix this, I tried setting overflow: hidden in the CSS: .ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: hidd ...

Using cURL in PHP to Handle JSON Data

I am trying to replicate the functionality of a website that uses AJAX POST requests using CURL in PHP. Typically, when monitoring POST requests with Firebug, you would see variable/value pairs. However, in this case, all you see is a single JSON string. ...

Looping through a MongoDB collection in Node.js using Express is a straightforward process

I am currently trying to showcase a collection - within the mongo shell it is quite simple. DB = testing collection = inventory > use testing switched to db testing > db.inventory.find(); // very easy and straightforward The issue I'm fac ...

What is the best way to redirect to a specific page when logging out of a website?

To begin, let me outline the situation at hand. We have two distinct websites - website-A and website-B. Each of these websites is hosted on separate domains. A user has the ability to log in to website-B's homepage through the login page of webs ...

The application is functional, however, the initial controller within is experiencing difficulties

Setting up a controller in my application based on a tutorial. The first two divs are displaying correctly but the ContraAss controller is not rendering and only shows {{info}}. What am I missing here? (NB. Probably something simple, but with limited exper ...

Guide on writing directly to a JSON object using ObjectMapper in Jackson JSON

I am attempting to output to a JSON object using Jackson JSON, but I am encountering issues with the current code. public class MyClass { private ObjectNode jsonObj; public ObjectNode getJson() { ObjectMapper mapper = new O ...

Move and place multimedia items using IE's drag and drop feature

Is there a way to enable the drag and drop feature across different browsers or windows using HTML5's native DnD API? I have noticed that when I set the data type to 'text' in Internet Explorer, it functions properly. However, if I attempt t ...

Use the accelerometer in JavaScript and Cordova to control the movement of an object, such as a ball

Having trouble figuring out how to move a ball using the accelerometer. Any tips on combining the accelerometer values with the ball movement? Waiting for accelerometer... <div id="heading">Waiting for heading...</div> <div id="ball" ...

The peculiar characteristics of the dragLeave event in various web browsers

I observed a peculiar behavior while working with drag events in Internet Explorer 11. It seems that adding a 'width' property to the elements triggers the dragLeave event, whereas without it, the event does not fire. Can anyone shed light on why ...

Having trouble generating a JSON file from user input upon clicking the button in a C# Windows Form application

Currently, I am in the process of developing a C# application using VS2017 windows form application. The primary functionality of this app is to take user input and save it into a JSON file. However, there's a limitation where only one user input can ...