在下面的Express函数中:
app.get('/user/:id', function(req, res){
res.send('user' + req.params.id);
});
什么是req和res?它们代表什么,它们意味着什么,它们做什么?
谢谢!
在下面的Express函数中:
app.get('/user/:id', function(req, res){
res.send('user' + req.params.id);
});
什么是req和res?它们代表什么,它们意味着什么,它们做什么?
谢谢!
当前回答
我注意到Dave Ward的回答中有一个错误(也许是最近的变化?) 查询字符串参数正在请求中。查询,而不是request.params。(见https://stackoverflow.com/a/6913287/166530)
请求。Params在默认情况下由路由中任何“组件匹配”的值填充。
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
并且,如果你已经配置express使用它的bodyparser (app.use(express. bodyparser());)也使用POST'ed formdata。(参见如何检索POST查询参数?)
其他回答
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, which will be "/people.json" when this particular action is triggered request.method, which will be "GET" in this case, hence the app.get() call. An array of HTTP headers in request.headers, containing items like request.headers.accept, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc. An array of query string parameters if there were any, in request.query (e.g. /people.json?foo=bar would result in request.query.foo containing the string "bar").
为了响应该请求,您可以使用响应对象来构建响应。扩展到人民。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);
});
请求和响应。
要理解req,请尝试console.log(req);。
我注意到Dave Ward的回答中有一个错误(也许是最近的变化?) 查询字符串参数正在请求中。查询,而不是request.params。(见https://stackoverflow.com/a/6913287/166530)
请求。Params在默认情况下由路由中任何“组件匹配”的值填充。
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
并且,如果你已经配置express使用它的bodyparser (app.use(express. bodyparser());)也使用POST'ed formdata。(参见如何检索POST查询参数?)