JSON String 没有到达服务器(如果你懂 express js 应该很容易解决)
JSON String not getting to the server (should be easy to solve if you know express js)
我正在使用 express js,但由于某种原因,服务器正在记录一个空对象 {}
而不是我发送的实际 JSON 字符串。我已经使用了很多其他技术,比如 Flask,这没有任何意义。
代码:
function upload () {
fetch("http://localhost:8080/chat", {
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "deska@gmail.com",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
app.post('/chat', function(req, res) {
let test = req.body;
console.log(test);
}
在“上传”功能上,我没有记录任何内容,而在服务器中,我得到了一个空对象 {}
我提到过。
如果你想知道我的问题,我将不胜感激。
谢谢。
更新:
问题应该在前端,因为使用 postman 发送 post 请求是可行的。
我认为错误的发生可能是因为您缺少 Content-Type
header。你可以试试这个:
function upload () {
fetch("http://localhost:8080/chat", {
headers: {
'Content-Type': 'application/json',
},
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "deska@gmail.com",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
您还应该确保在您的服务器中使用 express.json
中间件,这样:
app.use(express.json());
我正在使用 express js,但由于某种原因,服务器正在记录一个空对象 {}
而不是我发送的实际 JSON 字符串。我已经使用了很多其他技术,比如 Flask,这没有任何意义。
代码:
function upload () {
fetch("http://localhost:8080/chat", {
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "deska@gmail.com",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
app.post('/chat', function(req, res) {
let test = req.body;
console.log(test);
}
在“上传”功能上,我没有记录任何内容,而在服务器中,我得到了一个空对象 {}
我提到过。
如果你想知道我的问题,我将不胜感激。
谢谢。
更新:
问题应该在前端,因为使用 postman 发送 post 请求是可行的。
我认为错误的发生可能是因为您缺少 Content-Type
header。你可以试试这个:
function upload () {
fetch("http://localhost:8080/chat", {
headers: {
'Content-Type': 'application/json',
},
method: "POST",
body: JSON.stringify({
name: "Deska",
email: "deska@gmail.com",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
}
您还应该确保在您的服务器中使用 express.json
中间件,这样:
app.use(express.json());