简体   繁体   English

Node.js如何从请求中读取json数据?

[英]Node.js how to read json data from request?

I have a server as following: 我有一台服务器如下:

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

The request is sent from a client as: 请求从客户端发送为:

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

so far the connection fine. 到目前为止连接正常。

My problem is in the server: 我的问题出在服务器上:

console.log(req);

where I want to read the data I sent. 我想要读取我发送的数据。 How can I read { "a": "128", "b": "7" } from req ? 如何从req读取{ "a": "128", "b": "7" }

Although you're not mentioning it, your code looks like it's written for an Express environment. 虽然你没有提到它,但你的代码看起来像是为Express环境编写的。 My answer is targeted to this. 我的答案是针对这一点。

Make sure to use body-parser for Express. 确保使用Express的body-parser In case, your project depends on some generated boilerplate code, it's most likely already included in your main server script. 如果您的项目依赖于某些生成的样板代码,它很可能已经包含在您的主服务器脚本中。 If not: 如果不:

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

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

The parsed JSON can then be accessed through req.body : 然后可以通过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.
    // ...
});

For Express 4+, 对于Express 4+,

const express = require("express");
const app = express();

app.use(express.json());

Then, you can use req.body as expected. 然后,您可以按预期使用req.body

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM