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
包含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);});


