我正在制作一个简单的 Node.js Web 服务器,但在向服务器发送请求时遇到了麻烦。这是一个简单的 html“表单”示例。我发送了字符串化的 JSON 数据,但 req.body
为空。
HTML:
<!DOCTYPE html>
<html lang="ru" dir="ltr">
<head>
<meta charset="utf-8">
</head>
<body>
<input type="text" id="field" value="foo">
<button type="button" id="button">bar</button>
<script>
addElement = function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/database');
xhr.setRequestHeader('contentType', 'application/json; charset=utf-8');
var newElem = new Object();
newElem.name = field.value || "";
var requestData = JSON.stringify(newElem);
console.log(newElem);
// {name: "foo"}
xhr.send(requestData);
}
button.onclick = addElement;
</script>
</body>
</html>
Node 服务器代码:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.get("/", function(req,res){
res.sendFile(__dirname +"/index.html");
});
app.post('/database', function(req, res) {
console.log("req.body = ", req.body);
//expected output: req.body = ({name: foo})
//actual output: req.body = ()
});
app.listen(PORT, function() {
console.log('Server listening on ' + PORT);
});
最佳答案
将 contentType
替换为 Content-Type
。希望对您有帮助
关于javascript - 无法从 POST 请求检索 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57833060/