在以下Express函数中:
app.get('/user/:id', function(req, res){ res.send('user' + req.params.id); });
什么是req和res?它们代表什么,它们是什么意思,它们是做什么的?
req
res
谢谢!
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
request.query
/people.json?foo=bar
request.query.foo
"bar"
要响应该请求,您可以使用响应对象来构建响应。扩展people.json示例:
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); });