The XHR request fails to transmit a JSON object

Having a client-server express app, I am currently working on sending an XHR request from my frontend to the controller while passing JSON data. The code snippet from my frontend looks like this:

function handle_login(){
    var username_field = document.getElementById('input_username');
    var pass = document.getElementById('input_password');
    if(username_field.value!=null)console.log(username_field.value);
    console.log(pass.value);


    //window.location.href = "/loginAttempt/"+username.value+"-"+pass.value;
    var xhr = new XMLHttpRequest();
    var url = "/home_pogled"; 
     xhr.open("GET", url, true);
     xhr.setRequestHeader("Content-type", "application/json");
             var data = {
            username : username_field.value,
            password : pass.value
        }
        var json = JSON.stringify(data);
        xhr.send(json);

        xhr.onload = function() {//upon successful response
            var responseText = xhr.responseText;
            //console.log("Backend server response -" +responseText);
            // utilize the response
        };
        xhr.onerror = function() {
          console.log('There was an error!');
        };


}

Although I can send the request and confirm that the data is written into the JSON object before sending it, the issue arises when I console.log(req.body) in my controller upon receiving the request. The body displays as empty "{}" instead of containing the username and password values in a JSON object. What could be causing this discrepancy?

Answer №1

Front End:

To pass data in a GET request, it's best to use query parameters like shown in the code snippet below

let url = `/user_profile?name=${name_field.value}&email=${email_field.value}`; 

xhr.open('GET', url);

Back End (using Node.js):

With Node.js and Express, we can access these query parameters using req.query

let name = req.query.name;
 let email = req.query.email;

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

An error occurred: Cannot access the 'splice' property of an undefined value

//Screenshot <div v-for='(place) in query.visitPlaces' :key="place.name"> <div class="column is-4 is-narrow"> <b-field label="Nights"> <b-input type="text" v-model="place.nights" placeho ...

What's the best way to include CSS and Javascript in an HTML document?

I'm still getting the hang of CSS and JavaScript. I stumbled upon a cool countdown timer that I'd like to incorporate into my website, but I'm not quite sure how to place it where I envision it. Check out the timer here CSS: html,body{mar ...

The alert message fails to show up after the initial click on the close button

Whenever I click the x button to dismiss an alert message (indicating wrong data input in a form), the next time the user checks the form and enters incorrect data again, the alert message does not reappear after closing the x button. Any suggestions on ho ...

What is the process for accessing and utilizing the value returned by a promise in a separate file?

I have developed a small project to demonstrate an issue. There are a total of 5 files in this project: - A container file that includes all the dependency injections. - A service file containing the necessary functions to be executed. - A controller fil ...

Tips for minimizing Angular $digest-cycle invocations

Issue In my application, I have noticed that some callbacks are being called excessively during the $digest cycle. This high frequency of calls is causing performance concerns as these callbacks are triggered way more times than expected, sometimes even e ...

Exploring the Fusion of Material UI Searchbox and Autocomplete in React

Looking for help with my AppBar component from Material UI. I want the Searchbox field to function similarly to what is seen on https://material-ui.com/. It should appear as a Searchbox but display selectable options like Autocomplete after entering input. ...

Creating a dual-column checkbox design with CSS only

I'm working with a dynamically generated form element that can only be styled using CSS. I need help achieving a specific layout without making any HTML changes, except for the classes. The "element" and "formField" classes are common and cannot be mo ...

Why doesn't the default value in a React select update the selected input value and title when changed during rendering?

Through several attempts, I have successfully developed a React select dropdown that displays dynamic data for each sector. However, I am facing an issue with setting a default value upon rendering. Although I am able to add a static default value like S ...

Issue with ng-change function causing data not to load properly

I have added a data-ng-change='getSubjectsClasswise(classBean.class_id);' in the class <select> tag, but for some reason the subjects are not loading in the subject <select> tag. I have checked everything and it all seems fine, b ...

Maximizing the Potential of SWR with Any Type

I've created a custom hook that wraps around SWR: import useSWR from 'swr'; export enum MethodTypes { POST = 'POST', PUT = 'PUT', GET = 'GET', DELETE = 'DELETE', PATCH = 'PATCH' } ...

Error in Discord.JS: The function message.author.hasPermission is not recognized

As I was working on creating a new command for my discord.js bot to toggle commands on/off, I ran into some issues. Specifically, when I attempted to use the .hasPermission function, I encountered the following error message: TypeError: message.author.ha ...

Using NestJS to populate data will only populate the first element

I have a Mongoose schema in NestJS structured like this: ... @Prop() casinoAmount: number; @Prop() gameHyperLink: string; @Prop() casinoHyperLink: string; @Prop({ type: Types.ObjectId, ref: 'Game' }) games: Game[]; } I'm t ...

I am experiencing challenges with utilizing moment and angular filters

I was able to get this code working perfectly before the recent jsfiddle update. However, now it seems to be causing issues. Any assistance would be greatly appreciated. Let's start with the HTML code: <div ng-app="app" ng-controller="ctrl"> ...

What is the best method for creating numerous Popovers within a single ID?

Is it possible to create multiple popovers with the same ID? <div class="card-text"> <a href="#" id="seelabel" data-toggle="popover" data-trigger="hover" title="Inkscape" data-content= ...

Underscore - Evaluating the differences between two arrays of objects (positions)

Is it possible to compare arrays based on the changes in their element positions? I have an original array of objects that has one of its elements' values changed, resulting in a new array: origElements = [{id: 1, value: 50}, ...

An attribute bug in IE that is related to Jquery

Recently delving into Jquery, I came up with a basic script to display an image preview in a div when clicking on one of two links. <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'> ...

The drag-and-drop application failed to upload a video using Ajax

I am currently working on an application that allows users to upload files to a server with a drag and drop function. The app is functioning well for images, but occasionally encounters issues when trying to upload videos. I'm not certain if there&apo ...

axios in node does not support relative URLs

When running my node server, the code below works just fine axios.get('http://localhost:8080/myPath') // works Unfortunately, using relative paths does not work axios.get('/myPath') // doesn't work This is the error I encounter ...

Enhance a model in the Mean Stack with Node.js and Mongoose integration

Encountering an issue with updating a model in my API. Currently utilizing a Mean Stack with "express": "^4.14.0" and "mongoose": "^4.7.2", along with mongodb 3.2.11 Upon attempting to PUT the changes to the API, receiving an OK status, however, the resou ...

Error message "Function pointer is not a valid function" encountered in Angular version 1.2.25

I am encountering this error sporadically and without any specific pattern. Previously, the page was functioning correctly, but now this error is causing disruptions. Is there a recommended method for debugging or tracing the source of this problem? Err ...