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?