Express函数中的“res”和“req”参数是什么?

时间:2011-01-14 21:43:12

标签: node.js express

3 个答案:

答案 0 :(得分:236)

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中的HTTP标头数组,其中包含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);
});

答案 1 :(得分:22)

我注意到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配置为使用其bodysarser(app.use(express.bodyParser());)以及POST'ed formdata。 (见How to retrieve POST query parameters?

答案 2 :(得分:4)

请求和回复。

要了解req,请试用console.log(req);