node.js 如何在 Express 应用程序中使用 JSON POST 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10005939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I consume the JSON POST data in an Express application
提问by neuromancer
I'm sending the following JSON string to my server.
我将以下 JSON 字符串发送到我的服务器。
(
{
id = 1;
name = foo;
},
{
id = 2;
name = bar;
}
)
On the server I have this.
在服务器上我有这个。
app.post('/', function(request, response) {
console.log("Got response: " + response.statusCode);
response.on('data', function(chunk) {
queryResponse+=chunk;
console.log('data');
});
response.on('end', function(){
console.log('end');
});
});
When I send the string, it shows that I got a 200 response, but those other two methods never run. Why is that?
当我发送字符串时,它显示我收到了 200 响应,但其他两种方法从未运行。这是为什么?
回答by Pero P.
I think you're conflating the use of the responseobject with that of the request.
我认为您将response对象的使用与request.
The responseobject is for sending the HTTP response back to the calling client, whereas you are wanting to access the body of the request. See this answerwhich provides some guidance.
该response对象用于将 HTTP 响应发送回调用客户端,而您想要访问request. 请参阅此答案,该答案提供了一些指导。
If you are using valid JSON and are POSTing it with Content-Type: application/json, then you can use the bodyParsermiddleware to parse the request body and place the result in request.bodyof your route.
如果您使用有效的 JSON 并使用 POST 发布它Content-Type: application/json,那么您可以使用bodyParser中间件来解析请求正文并将结果放入request.body您的路由中。
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.listen(3000);
Test along the lines of:
按照以下方式进行测试:
$ curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://127.0.0.1:3000/
{"MyKey":"My Value"}
Updated for Express 4+
为 Express 4+ 更新
Body parser was split out into it's own npm package after v4, requires a separate install npm install body-parser
正文解析器在 v4 之后被拆分成它自己的 npm 包,需要单独安装 npm install body-parser
var express = require('express')
, bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.listen(3000);
Update for Express 4.16+
Express 4.16+ 更新
Starting with release 4.16.0, a new express.json()middleware is available.
从 4.16.0 版开始,提供了一个新的express.json()中间件。
var express = require('express');
var app = express();
app.use(express.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
app.listen(3000);
回答by chrisarton
For Express v4+
对于 Express v4+
install body-parser from the npm.
从 npm 安装 body-parser。
$ npm install body-parser
https://www.npmjs.org/package/body-parser#installation
https://www.npmjs.org/package/body-parser#installation
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res, next) {
console.log(req.body) // populated!
next()
})
回答by xims
Sometimes you don't need third party libraries to parse JSON from text. Sometimes all you need it the following JS command, try it first:
有时您不需要第三方库来解析文本中的 JSON。有时你只需要下面的 JS 命令,先试试看:
const res_data = JSON.parse(body);
回答by Daniel Thompson
For those getting an empty object in req.body
对于那些得到一个空物体的人 req.body
I had forgotten to set
headers: {"Content-Type": "application/json"}in the request. Changing it solved the problem.
我忘了headers: {"Content-Type": "application/json"}在请求中设置
。改变它解决了问题。
回答by anneb
@Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).
@Daniel汤普森提到,他已经忘记了添加{“内容类型”:“应用/ JSON”}的请求。他能够更改请求,但是,更改请求并不总是可能的(我们正在此处处理服务器)。
In my case I needed to force content-type: text/plain to be parsed as json.
就我而言,我需要强制将 content-type: text/plain 解析为 json。
If you cannot change the content-type of the request, try using the following code:
如果您无法更改请求的内容类型,请尝试使用以下代码:
app.use(express.json({type: '*/*'}));
Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:
而不是全局使用 express.json() ,我更喜欢仅在需要的地方应用它,例如在 POST 请求中:
app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
// echo json
res.json(req.body);
});
回答by SuRa
const express = require('express');
let app = express();
app.use(express.json());
This app.use(express.json) will now let you read the incoming post JSON object
这个 app.use(express.json) 现在让你读取传入的 post JSON 对象

