什么是“res”?和“req” Express 函数中的参数?
在下面的 Express 函数中:
app.get('/user/:id', function(req, res){
res.send('user' + req.params.id);
});
什么是 req
和 res
?它们代表什么、意味着什么、有什么作用?
谢谢!
In the following Express function:
app.get('/user/:id', function(req, res){
res.send('user' + req.params.id);
});
What are req
and res
? What do they stand for, what do they mean, and what do they do?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
req
是一个对象,其中包含有关引发事件的 HTTP 请求的信息。为了响应req
,您可以使用res
发回所需的 HTTP 响应。这些参数可以命名为任何名称。如果更清楚的话,您可以将该代码更改为:
编辑:
假设您有这个方法:
请求将是一个具有如下属性的对象(仅举几例):
request.url
,其中当触发此特定操作request.method
时,将是"/people.json"
,在这种情况下将是"GET"
,因此app.get()
调用。request.headers
中的 HTTP 标头数组,包含request.headers.accept
之类的项目,您可以使用它们来确定发出请求的浏览器类型、类型它可以处理的响应,无论它是否能够理解 HTTP 压缩等。request.query
中的查询字符串参数数组(如果有)(例如/people.json?foo =bar
将导致request.query.foo
包含字符串"bar"
)。要响应该请求,您可以使用响应对象来构建响应。扩展
people.json
示例:req
is an object containing information about the HTTP request that raised the event. In response toreq
, you useres
to send back the desired HTTP response.Those parameters can be named anything. You could change that code to this if it's more clear:
Edit:
Say you have this method:
The request will be an object with properties like these (just to name a few):
request.url
, which will be"/people.json"
when this particular action is triggeredrequest.method
, which will be"GET"
in this case, hence theapp.get()
call.request.headers
, containing items likerequest.headers.accept
, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.request.query
(e.g./people.json?foo=bar
would result inrequest.query.foo
containing the string"bar"
).To respond to that request, you use the response object to build your response. To expand on the
people.json
example:我注意到戴夫·沃德的回答中有一个错误(也许是最近的变化?):
查询字符串参数位于
request.query
中,而不是request.params
中。 (请参阅https://stackoverflow.com/a/6913287/166530)request.params
默认情况下填充路由中任何“组件匹配”的值,即,如果您已将express配置为使用其bodyparser(
app.use(express.bodyParser());
)也可以使用POST 后的表单数据。 (请参阅如何检索 POST 查询参数?)I noticed one error in Dave Ward's answer (perhaps a recent change?):
The query string paramaters are in
request.query
, notrequest.params
. (See https://stackoverflow.com/a/6913287/166530 )request.params
by default is filled with the value of any "component matches" in routes, i.e.and, if you have configured express to use its bodyparser (
app.use(express.bodyParser());
) also with POST'ed formdata. (See How to retrieve POST query parameters? )请求和响应。
要了解
req
,请尝试console.log(req);
。Request and response.
To understand the
req
, try outconsole.log(req);
.