简体   繁体   中英

I can't get a response from the server

I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.

this is my code

var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback 
xhr.onreadystatechange = function () { 
    if (xhr.readyState === 4 && xhr.status === 200) { 
        // Print received data from server 
        result.innerHTML = this.responseText; 
    } 
}; 
// Converting JSON data to string 
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request 
xhr.send(data);

I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.

It's better to use onload instead of onreadystatechange

xhr.onload = function() {
  if (xhr.status == 200) { 
    console.log(`Response length = ${xhr.response.length}`);
    // store xhr.response here somewhere
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM