【问题标题】:Node.js how to read json data from request?Node.js 如何从请求中读取 json 数据?
【发布时间】:2017-05-03 20:13:20
【问题描述】:

我的服务器如下:

app.post('/', function(req, res, next) {
   console.log(req);
   res.json({ message: 'pppppppppppppssssssssssssss ' });   
});

请求从客户端发送为:

$.ajax({
    type: "POST",
    url: self.serverURI,
    data: JSON.stringify({ "a": "128", "b": "7" }),
    dataType: 'json',
    success: function (result) {
        console.log(result);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr);
    }
});

到目前为止,连接正常。

我的问题出在服务器上:

console.log(req);

我想在哪里读取我发送的数据。如何从req 读取{ "a": "128", "b": "7" }

【问题讨论】:

    标签: json node.js express


    【解决方案1】:

    虽然您没有提及它,但您的代码看起来像是为Express 环境编写的。我的回答就是针对这个的。

    确保使用 body-parser 表示 Express。如果您的项目依赖于一些生成的样板代码,它很可能已经包含在您的主服务器脚本中。如果没有:

    var bodyParser = require('body-parser');
    app.use(bodyParser.json());
    

    使用 npm 安装:npm install body-parser --save

    然后可以通过req.body访问解析后的JSON:

    app.post('/', function(req, res, next) {
        console.log(req.body); // not a string, but your parsed JSON data
        console.log(req.body.a); // etc.
        // ...
    });
    

    【讨论】:

    • 非常感谢,它成功了。最后噗噗噗。如果您能解释我如何通过“res”参数向客户端发送这样的 JSon,那就太好了:)
    • res.json(object) 是正确的方法。正如您的示例代码中已经给出的那样。
    • 我阅读了很多教程。有的使用“res.json(object)”,有的使用“res.end(something)”,对于新手来说很困惑。
    • res.json 将自动将响应 content-type 标头设置为 application/json,而 res.send 将默认设置 text/html。如果您要返回 JSON,请务必使用 res.json 函数。
    【解决方案2】:

    对于 Express 4+,

    const express = require("express");
    const app = express();
    
    app.use(express.json());
    

    然后,您可以按预期使用req.body

    app.post("/api", (req, res) => {
      /*
        If the post request included { data: "foo" },
        then you would access `data` like so:
      */
      req.body.data
      ...
    });
    

    【讨论】:

      猜你喜欢
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 2013-11-01
      • 1970-01-01
      相关资源
      最近更新 更多