the `req.body` method fetches an object with a property named `json

Having an issue with accessing data from req.body in my form created with JS

{ 'object Object': '' }

//when using JSON.stringify:
{ '{"A":"a","B":"b","C":"c"}': '' }

Client

    var body = `{
        "A": "a",
        "B": "B",
        "C": "c"
    }`
    body = JSON.parse(body) // Object { A: "a", B: "b", C: "C" }
    body = JSON.stringify(body) // "{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"}"
const opts = {
  method: "POST",
  headers: {
  "content-type": "application/x-www-form-urlencoded",
},
body
}
console.log(body)
    fetch(`${document.URL}/post`, opts).then((response) => {
        console.log(response.status);
        console.log(response.json());

    })
})

server

router.post("/post", auth, async (req, res) => {
    console.log(req.body)
    res.status(201)
    res.end()
});

Seeking help on converting this format

{ '{"A":"a","B":"b","C": "c"}': '' }

to desired format:

{ A: "a", B:"b", C: "c"}

Solution

Special shoutout to Barmar and Phil for providing the solution.

Simply replace

"content-type": "application/x-www-form-urlencoded"
with
"Content-type": "application/json",
in the headers. Additionally, add app.use(express.json()) in server.js file.

Answer №1

take a look at this snippet of code

let data = { '{"X":"x","Y":"y","Z": "z"}': '' };
let keys = Object.keys(data);

console.log(JSON.parse(keys[0]));

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

The issue of invalid JSON due to special characters when creating an object using DataContractJsonSerializer

When attempting to serialize an object that contains special characters like ø or æ, I am encountering an issue where the JSON output is being truncated. An example without special characters looks like this: {"availability":"busy","name":"test","visib ...

Having trouble updating the state value using useState in React with Material-UI

I have developed a unique custom dialog component using Material-UI const CustomDialog = (props) => { const [dialogOpenState, setOpen] = React.useState(props.dilaogOpenProp); return ( <> <CssBaseline /> <Dialog ...

Is Next.js compatible with CSS caching?

I'm currently working on a project with Next.js (version 12.1.0) and SCSS modules. I've noticed that my CSS seems to be caching extremely aggressively, requiring me to restart the server (npm run next dev) in order to clear it. Has anyone else en ...

Using Angular to create a dynamic form with looping inputs that reactively responds to user

I need to implement reactive form validation for a form that has dynamic inputs created through looping data: This is what my form builder setup would be like : constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ ...

Guide on how to display a personalized token in the header within Swagger UI(swagger.json) using nodejs

As I develop a Restful server using ExpressJs, I have incorporated swagger-jsdoc for API documentation. The related files are shown below. The image (header.png) depicts how I envision my header to appear in the swagger UI. However, upon accessing my swagg ...

Transforming ajax code into node.js

After mastering ajax calls for client-server interaction, I am facing a challenge in converting my code to a server-side node compatible JS using http requests. Despite reading various tutorials, I am struggling to adapt them to fit with my current code st ...

Using jest.fn() to simulate fetch calls in React

Can anyone explain why I have to include fetch mock logic within my test in order for it to function properly? Let's take a look at a simple example: Component that uses fetch inside useEffect and updates state after receiving a response: // Test.js ...

Issue with Angular filter not being effective within ng-repeat

For all code regarding this issue, please visit: Filter: <input type="text" ng-model="search"> <tr ng-repeat="(id, group) in groups | filter:search" class="editing-{{group.editing}}"> The goal is to have the rows filtered out based on the in ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

Troubleshooting JSON-RPC Requests in Python with jsonrpcclient

Recently, I attempted to utilize the API on random.org and encountered an issue with the code provided below: from jsonrpcclient import request import requests reply = requests.post("https://api.random.org/json-rpc/4/invoke", params = {"met ...

Transmitting a variable string from JavaScript to PHP through AJAX

How can I pass a variable value from an HTML page using JavaScript to PHP? In my index.php file, I have the following code: $amount = $_GET['pricenumb']; echo $amount; Here is the JavaScript code I used to call on click of a button and send th ...

Unable to establish a local dependency link with npm

Attempting to connect my local project testabc123 to myproject using the usual method: cd testabc123 npm link cd ../myproject npm link testabc123 However, encountering an error message: npm ERR! code E404 npm ERR! 404 Not Found - GET http://registry.npmjs ...

Error encountered while deserializing Json in C#: Null class

My PHP code is working perfectly fine and returning the correct JSON response: if ($result->num_rows === 1) { $sql = ("SELECT username, email, plan, activationdate, terminationdate FROM users WHERE username = '$username' LIMIT 1" ...

What are the steps to implement a Bottom Navigation bar in iOS and a Top Navigation bar in Android using NativeScript Angular?

For my project, I decided to utilize the tns-template-tab-navigation-ng template. I am currently working on creating a WhatsApp clone, and in iOS, it features a bottom navigation bar while in Android, it has a top navigation bar. I am looking for guidance ...

Using VueJS Single File Components can cause issues with the example code for "Custom Popups" in the Google Maps API

Trying to implement a unique Google Maps popup following the provided documentation. After copying and pasting the official Google example code into a VueJS jsFiddle, the custom marker functions correctly as intended. It remains in the designated area eve ...

The object identified as "#<Object>" does not contain a function called 'resetMaxAge' in NodeJS

I'm facing a strange issue and I need help troubleshooting it. I attempted to use connect-mongo with express-session, but it's not functioning as expected. Here is a snippet of my server.js file: var session = require('express-sessi ...

Utilizing a Promise in NodeJS and Express to effectively capture the writing functionality of the HTTP module

Currently, I am in the process of developing an Express application with the following components: NodeJS v8 express (latest version) As I delved into the workings of the onHeaders module and observed how it alters the HTTP headers, I became keen on lev ...

Struggles with Cross-Origin Resource Sharing in Node.js, Express, and React

After successfully deploying a small application, everything seemed to be working fine during development! The application is hosted on my PLESK Server and it's running smoothly so far. While I am able to request a basic JSON with no issues, other A ...

Handle the URL in a manner similar to Express for extracting request parameters in a get operation

Is there a way to extract the parameters from a uri string in a manner identical to Express? Using regex or other methods may not yield consistent results, as it may differ from how Express interprets them. Ideally, I am looking for a solution that mirrors ...

Guide to setting up a Node, Express, Connect-Auth, and Backbone application architecture for server-side development

As someone who primarily works on the client-side, I have recently ventured into the realm of server-side JavaScript. My initial plan for my first Node.js application involves a server-side setup that primarily serves an empty shell along with a plethora o ...