gpt4 book ai didi

javascript - AJAX POST JSON 从 javascript 到 nodejs 服务器

转载 作者:行者123 更新时间:2023-11-30 08:32:13 25 4
gpt4 key购买 nike

我正在尝试将 JSON 对象从 javaScript 发送到 node.js 服务器。我正在使用标准的 XMLHttpRequest 从 javascript 和标准的 node.js 代码发送它。

两个代码似乎可以正常通信,但是 node.js 总是给我一个空的 JSON 对象。我不太确定我做错了什么。

这是我的 javascript 代码:

<html>
<head>
<script>
function xhrPost() {
var data = {"name":"John", "time":"2pm"};
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});

xhr.open("POST", "http://[serverIP]:8080/addUser");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(data));
}
</script>
</head>

<body onload="xhrPost()">

</body>
</html>

这是我的 node.js 代码:

var express = require("express");
var myParser = require("body-parser");
var app = express();

app.use(myParser.urlencoded({extended : true}));
app.post("/addUser", function(request, response) {
console.log(request.body); // this line allways produce {}
response.send("Message received.");
response.end();
});

app.listen(8080);

最佳答案

您必须使用 myParser.json() 作为中间件。在 https://github.com/expressjs/body-parser#bodyparserjsonoptions 中查看更多相关信息

关于javascript - AJAX POST JSON 从 javascript 到 nodejs 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35956309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com