javascript - 在 NodeJS api 服务器中从客户端获取 JSON 内容

标签 javascript json node.js express

我想在基于 nodejs 服务器的客户端使用 ajax 获取我发布的 JSON 对象的内容。

如果我在客户端有如下代码:

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>

    $('#form').click(function(e){
        e.preventDefault();

        hellodata = {
                id : '1234',
                content: 'hello'
        };

        $.ajax({
            url : "http://localhost:3000/savedata",
            type: "POST",
            data : hellodata,
            success: function(data, textStatus, jqXHR)
            {
                //data - response from server
            },
            error: function (jqXHR, textStatus, errorThrown)
            {

            }
        });
    });

</script>

如何获取服务端的参数id和content?

server.post("/savedata", function(req, res){
      //I get here after doing the ajax post and I want to show here the content of hellodata json
});

谢谢!

最佳答案

要在您的POST 请求中读取JSON,您应该使用body-parser:

npm install --save body-parser

然后添加到你的服务器端:

var bodyParser = require('body-parser');

// parse application/json
server.use(bodyParser.json());

server.post("/savedata", function(req, res){
   console.log(req.body);
});

您还必须使用以下内容更新您的 ajax 请求:

contentType: "application/json",
data: JSON.stringify(hellodata),

关于javascript - 在 NodeJS api 服务器中从客户端获取 JSON 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29882601/

相关文章:

javascript - 验证 sendKeys 导致页面对象文件导致未定义错误(Protractor)

php - PHP 中的 JSON – 嵌套数组

javascript - Socket.io 客户端同时连接到多个服务器

php - 无需重新加载页面的聊天客户端/帖子

javascript - 有没有办法在从同一子列表中选择下拉值时禁用子列表字段。 SuiteScript 2.0 getSublistField 方法不起作用

php - json、ajax、php和mySQL的设计结构

python - 使用 python 将纯 JSON 发送到 gRPC 服务器

javascript - nodemon,babel-node : how to set environment variable?

javascript - 非法返回声明

javascript - 在使用 Promise.all 运行的函数中使用 wait 后,Var 具有相同的值