在以下快递功能中:

app.get('/user/:id', function(req, res){
    res.send('user' + req.params.id);
});

什么是 reqres?他们代表什么,他们是什么意思,他们做什么?

谢谢!

有帮助吗?

解决方案

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 包含字符串 "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);
});

其他提示

我注意到戴夫·沃德(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使用其BodyParser(app.use(express.bodyParser());)还有邮政formdata。 (看 如何检索邮政查询参数? )

请求和响应。

理解 req, , 试用 console.log(req);.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top