【问题标题】:Get JSON content from client in NodeJS api server从 NodeJS api 服务器中的客户端获取 JSON 内容
【发布时间】:2015-07-05 03:07:53
【问题描述】:

我想从基于 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和内容?

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
});

谢谢!

【问题讨论】:

  • 你在使用express?
  • 是的,我正在使用快递
  • 您没有发布 JSON。您正在发布表单编码数据。

标签: javascript json node.js express


【解决方案1】:

要在您的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),

【讨论】:

  • @Alhar 很好,如果有帮助,您可以接受答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 2022-05-11
相关资源
最近更新 更多