【发布时间】: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