在以下Express功能中:
app.get('/user/:id', function(req, res){
res.send('user' + req.params.id);
});
Run Code Online (Sandbox Code Playgroud)
什么是req和res?他们代表什么,他们是什么意思,他们做了什么?
谢谢!
Dav*_*ard 248
req是一个对象,包含有关引发事件的HTTP请求的信息.作为回应req,您使用res发送回所需的HTTP响应.
这些参数可以命名为任何名称.如果更清楚,您可以将该代码更改为:
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Run Code Online (Sandbox Code Playgroud)
编辑:
说你有这个方法:
app.get('/people.json', function(request, response) { });
Run Code Online (Sandbox Code Playgroud)
请求将是一个具有这些属性的对象(仅举几例):
request.url,这将"/people.json"是触发此特定操作的时间request.method,"GET"在这种情况下,因此app.get()呼叫.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) {
// 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);
});
Run Code Online (Sandbox Code Playgroud)
Myr*_*tol 24
我注意到Dave Ward的答案中有一个错误(也许是最近的更改?):查询字符串参数request.query不在request.params.(参见/sf/answers/483930121/)
request.params 默认情况下,填充路径中任何"组件匹配"的值,即
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
Run Code Online (Sandbox Code Playgroud)
并且,如果您已将express配置为使用其bodyparser(app.use(express.bodyParser());)以及POST'ed formdata.(请参阅如何检索POST查询参数?)
| 归档时间: |
|
| 查看次数: |
162612 次 |
| 最近记录: |