req
是一个包含有关引发事件的 HTTP 请求信息的对象。为了响应 req
,您使用 res
发送所需的 HTTP 响应。
这些参数可以被命名为任何名称。如果更加清晰,您可以将代码更改为以下内容:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
编辑:
假设您有以下方法:
app.get('/people.json', function(request, response) { });
请求将是一个带有以下属性的对象(仅列举几个):
request.url
,在触发此特定操作时将为"/people.json"
request.method
,在此情况下将为"GET"
,因此调用了app.get()
- HTTP头信息的数组,包含在
request.headers
中,其中包含诸如request.headers.accept
之类的项目,您可以使用它来确定发出请求的浏览器类型、它能处理哪种类型的响应、是否能够理解HTTP压缩等。
- 如果有任何查询字符串参数,则在
request.query
中包含它们的数组(例如:/people.json?foo=bar
将导致request.query.foo
包含字符串"bar"
)。
要响应该请求,您可以使用响应对象构建响应。以people.json
示例为例进行扩展:
app.get('/people.json', function(request, response) {
response.contentType('application/json');
var people = [
{ name: 'Dave', location: 'Atlanta' },
{ name: 'Santa Claus', location: 'North Pole' },
{ name: 'Man in the Moon', location: 'The Moon' }
];
var peopleJSON = JSON.stringify(people);
response.send(peopleJSON);
});
req
=="request"
//res
=="response"
- nilon