【问题标题】:I can't get a response from the server我无法从服务器获得响应
【发布时间】:2020-11-05 14:41:44
【问题描述】:

我遵循了一些关于如何将 json 对象发送到服务器的指南(使用 node.js 编写),但它不起作用,我不知道出了什么问题。我知道我的服务器工作正常,因为我在邮递员上对其进行了测试,所以问题出在我的 js 代码上,我看到的所有教程都遵循类似的 XMLHttpRequest 格式。

这是我的代码

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);

我使用 document.write 来检查代码在哪里停止工作但一切都通过了(因为 document.write 打印了一些东西),我怀疑 xhr.send(data) 有什么错误/缺失,但我不知道什么。最后,回调不会打印任何内容。

【问题讨论】:

  • 那么错误信息是什么?
  • 这些根本不是消息
  • 我的 IDE 是括号
  • 那么,客户端(浏览器)中的错误信息是什么,即如果您打开 devtool,控制台上有什么?
  • 谢谢你的信息,我不知道

标签: javascript node.js json xml server


【解决方案1】:

最好使用onload 而不是onreadystatechange

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

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 2017-06-25
    • 2020-07-17
    • 2019-08-20
    • 2015-11-14
    相关资源
    最近更新 更多