Javascript 使用 Node.js 和 Express POST 时如何访问请求正文?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11625519/
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 to access the request body when POSTing using Node.js and Express?
提问by TheBlueSky
I have the following Node.js code:
我有以下 Node.js 代码:
var express = require('express');
var app = express.createServer(express.logger());
app.use(express.bodyParser());
app.post('/', function(request, response) {
response.write(request.body.user);
response.end();
});
Now if I POST something like:
现在,如果我发布类似的内容:
curl -d user=Someone -H Accept:application/json --url http://localhost:5000
I get Someone
as expected. Now, what if I want to get the full request body? I tried doing response.write(request.body)
but Node.js throws an exception saying "first argument must be a string or Buffer" then goes to an "infinite loop" with an exception that says "Can't set headers after they are sent."; this also true even if I did var reqBody = request.body;
and then writing response.write(reqBody)
.
我得到Someone
了预期的结果。现在,如果我想获得完整的请求正文怎么办?我尝试这样做,response.write(request.body)
但 Node.js 抛出一个异常,说“第一个参数必须是字符串或缓冲区”,然后进入“无限循环”,异常显示“发送后无法设置标头。”;即使我做了var reqBody = request.body;
然后写作也是如此response.write(reqBody)
。
What's the issue here?
这里有什么问题?
Also, can I just get the raw request without using express.bodyParser()
?
另外,我可以只获取原始请求而不使用express.bodyParser()
吗?
采纳答案by Hector Correa
Express 4.0 and above:
Express 4.0及以上:
$ npm install --save body-parser
$ npm install --save body-parser
And then in your node app:
然后在您的节点应用程序中:
const bodyParser = require('body-parser');
app.use(bodyParser);
Express 3.0 and below:
Express 3.0 及以下:
Try passing this in your cURL call:
尝试在您的 cURL 调用中传递它:
--header "Content-Type: application/json"
--header "Content-Type: application/json"
and making sure your data is in JSON format:
并确保您的数据采用 JSON 格式:
{"user":"someone"}
{"user":"someone"}
Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:
此外,您可以在 node.js 代码中使用 console.dir 来查看对象内的数据,如下例所示:
var express = require('express');
var app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
console.dir(req.body);
res.send("test");
});
app.listen(3000);
This other question might also help: How to receive JSON in express node.js POST request?
另一个问题也可能有帮助:How to receive JSON in express node.js POST request?
If you don't want to use the bodyParser check out this other question: https://stackoverflow.com/a/9920700/446681
如果您不想使用 bodyParser,请查看其他问题:https://stackoverflow.com/a/9920700/446681
回答by rustyx
Starting from express v4.16there is no need to require any additional modules, just use the built-in JSON middleware:
从express v4.16开始不需要任何额外的模块,只需使用内置的JSON 中间件:
app.use(express.json())
Like this:
像这样:
const express = require('express')
app.use(express.json()) // <==== parse request body as JSON
app.listen(8080)
app.post('/test', (req, res) => {
res.json({requestBody: req.body}) // <==== req.body will be a parsed JSON object
})
Note - body-parser
, on which this depends, is already includedwith express.
注意 - body-parser
,这取决于,已经包含在 express 中。
Also don't forget to send the header Content-Type: application/json
也不要忘记发送标题 Content-Type: application/json
回答by Walter Roman
As of Express 4, the following code appears to do the trick.
Note that you'll need to install body-parser
using npm
.
从 Express 4 开始,以下代码似乎可以解决问题。请注意,您需要body-parser
使用npm
.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(8888);
app.post('/update', function(req, res) {
console.log(req.body); // the posted data
});
回答by Gautam
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var port = 9000;
app.post('/post/data', function(req, res) {
console.log('receiving data...');
console.log('body is ',req.body);
res.send(req.body);
});
// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);
This will help you. I assume you are sending body in json.
这会帮助你。我假设你在 json 中发送 body。
回答by Shivam Gupta
For 2019, you don't need to install body-parser
.
对于 2019 年,您无需安装body-parser
.
You can use:
您可以使用:
var express = require('express');
var app = express();
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.listen(8888);
app.post('/update', function(req, res) {
console.log(req.body); // the posted data
});
回答by Manivannan
This can be achieved without body-parser
dependency as well, listen to request:data
and request:end
and return the response on end of request, refer below code sample. ref:https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body
此,可以实现无body-parser
依赖关系,以及,听取request:data
和request:end
,并返回对请求端的响应时,参考下面的代码示例。参考:https: //nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body
var express = require('express');
var app = express.createServer(express.logger());
app.post('/', function(request, response) {
// push the data to body
var body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
// on end of data, perform necessary action
body = Buffer.concat(body).toString();
response.write(request.body.user);
response.end();
});
});
回答by Peter Lyons
Try this:
尝试这个:
response.write(JSON.stringify(request.body));
That will take the object which bodyParser
has created for you and turn it back into a string and write it to the response. If you want the exact request body (with the same whitespace, etc), you will need data
and end
listeners attached to the request before and build up the string chunk by chunk as you can see in the json parsing source code from connect.
这将获取bodyParser
为您创建的对象并将其转换回字符串并将其写入响应。如果您想要确切的请求正文(具有相同的空格等),您将需要data
和end
之前附加到请求的侦听器并逐块构建字符串,如您在json 解析来自 connect 的源代码中看到的那样。
回答by ebohlman
What you claim to have "tried doing" is exactly what you wrote in the code that works "as expected" when you invoke it with curl.
您声称“尝试做的”正是您在代码中编写的内容,当您使用 curl 调用它时“按预期”工作。
The error you're getting doesn't appear to be related to any of the code you've shown us.
您收到的错误似乎与您向我们展示的任何代码无关。
If you want to get the raw request, set handlers on request
for the data
and end
events (and, of course, remove any invocations of express.bodyParser()
). Note that the data
events will occur in chunks, and that unless you set an encoding for the data
event those chunks will be buffers, not strings.
如果您想获得原始请求,请request
为data
和end
事件设置处理程序(当然,删除对 的任何调用express.bodyParser()
)。请注意,data
事件将以块的形式发生,除非您为data
事件设置编码,否则这些块将是缓冲区,而不是字符串。
回答by Shujaath Khan
If you're lazy enough to read chunks of post data. you could simply paste below lines to read json.
如果你懒得阅读大量的帖子数据。您可以简单地粘贴以下几行来读取 json。
Below is for TypeScript similar can be done for JS as well.
下面是 TypeScript 的类似也可以用于 JS。
app.ts
应用程序
import bodyParser from "body-parser";
// support application/json type post data
this.app.use(bodyParser.json());
// support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
In one of your any controller which receives POST call use as shown below
在您接收 POST 调用的任何控制器之一中,如下所示
userController.ts
用户控制器.ts
public async POSTUser(_req: Request, _res: Response) {
try {
const onRecord = <UserModel>_req.body;
/* Your business logic */
_res.status(201).send("User Created");
}
else{
_res.status(500).send("Server error");
}
};
_req.body should be parsing you json data into your TS Model.
_req.body 应该将您的 json 数据解析为您的 TS 模型。
回答by balintn
I'm absolutely new to JS and ES, but what seems to work for me is just this:
我对 JS 和 ES 完全陌生,但似乎对我有用的是:
JSON.stringify(req.body)
Let me know if there's anything wrong with it!
让我知道它是否有任何问题!