javascript - 无法从 POST 请求检索 JSON 数据

标签 javascript node.js xmlhttprequest

我正在制作一个简单的 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/

相关文章:

javascript - Bootstrap JS 验证器和表单提交

javascript - 带有 webpack 的 Vue.js 不提供压缩的 GZIP .js 文件

javascript - 不同的浏览器窗口在electronic js中应具有不同的菜单选项

javascript - 谷歌浏览器 : A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true

javascript - 快速表单处理,无需重定向。有数据但没有preventDefault,但重定向。不使用 PreventDefault 进行重定向,但没有数据

javascript - AngularJS - Controller 中的参数绑定(bind)

javascript - 计数器功能设定值

javascript - 根据两个整数之间的值返回一个字符串

Node.JS 字符串仅匹配第一个字符

c# - 如何将字节数组转换为xml?