What is the process of including JSON data in a GET request for an XMLHttpRequest?

I am facing an issue with setting JSON data in a GET request. I have tried the following: Using it as a POST request (it works fine when used as a POST request)

xhr.open("GET", "http://localhost/test", true);
body = JSON.stringify({"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="264e435f664b474f4a0845494b">[email protected]</a>", "password": "101010"});
xhr.send(body);

Trying as a query string:

var json = {"hello": "world"};
var url = "http://localhost/test?data=" + encodeURIComponent(JSON.stringify(json));
xhr.open("GET", url, true);
xhr.send();

In the backend method, req.json returns null, even though I can see the query string.

Interestingly, it works in Postman if I set JSON data to the body. The backend shows that the JSON data is part of the request.

P.S.: In a previous project where I used the same backend framework but jQuery for the frontend instead of pure JS, the ajax method worked without any issues.

Answer №1

After a two-month break from web development, I found myself asking some pretty silly questions. Although I'm not familiar with node.js, I believe it behaves in a certain way. I finally recalled the correct method - instead of using "localhost?data={a: 9}", the right approach is actually "localhost?a=9". This allows the backend to interpret all query variables as input in the Rest interface. Special thanks to @evolutionxbox for pointing me in the right direction.

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 $scope within the $ionicplatform is not functioning as expected

I've been working on an application, but it doesn't seem to be functioning correctly. Typically, when we add a value to the scope, I expect it to update in the application. Here is the snippet from index.html: <body ng-app="starter"> <i ...

What are the solutions for resolving CORS issues with a local HTML file using three.js?

I have been attempting to create a sphere using three.js with an image texture, but no matter if it's a local image or an https image online, I always encounter the following error: Access to image at 'file:///C:/Users//.....//sun.jpg' fro ...

When using PHP to work with JSON arrays, it is necessary to specify an index in order to retrieve the value

My json array has the following structure: [{"name":"title_one","value":"something"},{"name":"title_two","value":"something 2"},{"name":"title_three","value":"something three"}] Typically, I access values in the array like this: $configarray = json_deco ...

How can I remove all double quotes within a JSON dataset {} in a bash script, specifically the ones between the double quotes?

Currently, I am facing a challenge with a massive 20GB JSON file containing realty records. For example: {"id":2545,"name":"No cribs (infant beds) available"},{"description": "Here is some text with a <a href=\"stupidurl.com\">click here& ...

Customizing the Slider Range with HTML DOM Style's BackgroundImage Attribute

I have a slider range that I'd like to modify using JavaScript. Specifically, I want to change its background-image property. To achieve this, I attempted the following script: document.getElementById("range").style.backgroundImage = "linear-gradient ...

Ways to deactivate a button using CSS

I need to use Javascript to disable a link based on its id. By default, the link is invisible. I will only enable the link when the specific id value comes from the backend. HTML <li id="viewroleId" style="display: none;"> <a href="viewrole" ...

What is the best way to alter a specific value within an object without losing other important data?

I'm currently working on developing a function that will activate when the count either matches or is half the initial price required to open, and it should not reset to false even if the count drops back to 0. Below is some sample data: openData = { ...

AJAX Post data transmission on the network: Enhancing data formatting

For my AJAX post call, I need to format the data differently. The server is expecting the data in a specific format when viewed in Chrome Network Headers details. My task is to update the JavaScript code below to meet this formatting requirement: percenta ...

Issue: [$injector:unpr] The provider ngCsvProvider is not recognized, referenced within the ngCsv module and utilized in the dynamicDemoController

Let me set the stage for you: We have A.js, which defines the main module. We also have B.js, which is lazy-loaded after angular bootstrapping and contains a controller along with some directives. Contents of A.js: var APP = angular.module('app.he ...

Uncaught Error: The property 'post' is not defined and cannot be read

As I strive to organize my code by separating it into different JavaScript files, the use of 'import/export' or 'module.exports/require' for importing the app module is causing issues. It restricts me from utilizing methods like post an ...

The powers of jQuery and CSS selectors

Previously, I utilized the following code to extract text from the data-placeholder attribute and apply it as a placeholder for my div. [contentEditable=true]:empty:not(:focus):before { content:attr(data-placeholder) } While this method worked well b ...

Exploring the possibilities of integrating Storybook/vue with SCSS

After creating a project with vue create and installing Storybook, everything was running smoothly. However, as soon as I added SCSS to one of the components, I encountered the following error: Module parse failed: Unexpected token (14:0) File was process ...

When I attempt to dynamically insert a URL into the backgroundImage property using JSS in React with Material-UI, the image does not

If I want to statically display an image by importing it and using the variable in the useStyles function, I can do so like this: import React from 'react' import { makeStyles } from '@material-ui/core/styles' import { Box } from &apos ...

When displaying content within an iframe, toggle the visibility of div elements

I'm attempting to toggle the visibility of certain page elements based on whether the page is loaded in an iframe. <script>this.top.location !== this.location && (this.top.location = this.location);</script> The above code succes ...

Navigating through AngularJS routes leads to an unexpected directory being added

Assigned to an AngularJS project after the departure of a team member, I found myself navigating unfamiliar territory as a Python/Java developer. Despite its outdated AngularJS version 1.0.8, I aim to modernize the system once it's stable. An issue h ...

Combining audio files together with Node.JS

Edit: The initial question was deemed too broad, so I have simplified it to focus on one main query: How can I seamlessly play a sequence of audio files within a web page (specifically using React) without any gaps between each play? I have taken an aud ...

Encountered an issue while attempting to parse the native JSON Data

Attempting to revive an old project using Android Studio is proving to be a challenge. The process consistently fails, accompanied by the following error message: Error:Failed to read native JSON data Use JsonReader.setLenient(true) to accept malforme ...

Browsing through JSON data and divvying up the contents into a trio of columns

I am facing a challenge with displaying a large number of JSON objects in an array in three columns on the front-end. What is the most efficient way to loop through these JSON objects and showcase them evenly across the three columns? These objects consist ...

Retrieve specific information from a nested JSON structure and combine it into a unified array

I am struggling to extract specific data from the JSON below and add them to a single array. I have managed to extract all the text values inside the block, but I am facing difficulty in pushing it to a single array. The code snippet I used for extraction ...

Having trouble uploading a file with Parse.File in an express web application

Currently, I am developing an express web application with a Parse backend. To render webpages, I am utilizing .ejs files. Upon clicking the submit button on the file upload form, Express routes me to testfile.js where I am using the Parse.File method to u ...