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

我有一个服务器如下:

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" }

虽然你没有提到它,但你的代码看起来像是为Express环境编写的。 我的答案是针对这一点。

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

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

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

parsing后的JSON可以通过req.body访问:

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