Answers:
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()
称为通话。request.headers
,包含诸如之类的项目request.headers.accept
,您可以使用它们确定哪种类型的浏览器发出请求,可以处理哪种响应,是否能够理解HTTP压缩等。request.query
(例如,/people.json?foo=bar
将导致request.query.foo
包含string "bar"
)。要响应该请求,您可以使用响应对象来构建响应。扩展people.json
示例:
app.get('/people.json', function(request, response) {
// We want to set the content-type header so that the browser understands
// the content of the response.
response.contentType('application/json');
// Normally, the data is fetched from a database, but we can cheat:
var people = [
{ name: 'Dave', location: 'Atlanta' },
{ name: 'Santa Claus', location: 'North Pole' },
{ name: 'Man in the Moon', location: 'The Moon' }
];
// Since the request is for a JSON representation of the people, we
// should JSON serialize them. The built-in JSON.stringify() function
// does that.
var peopleJSON = JSON.stringify(people);
// Now, we can use the response object's send method to push that string
// of people JSON back to the browser in response to this request:
response.send(peopleJSON);
});
我在Dave Ward的答案中发现一个错误(也许是最近的变化?):查询字符串参数位于request.query
,而不是request.params
。(请参阅https://stackoverflow.com/a/6913287/166530)
request.params
默认情况下,使用路由中任何“组件匹配”的值填充,即
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
并且,如果您已配置express将其bodyparser(app.use(express.bodyParser());
)也用于POST的formdata。(请参阅如何检索POST查询参数?)
req
=="request"
//res
=="response"