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

exp*_*oob 170 node.js express

在以下Express功能中:

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

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

谢谢!

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()呼叫.
  • 一个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);
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,这应该是在express.js网站的主页上. (7认同)
  • 如果有人在寻找`req`和`res`结构的详细信息,请在明确的文档中说明:`req`:http://expressjs.com/en/api.html#req,`res`:http:/ /expressjs.com/en/api.html#res (7认同)
  • 您可以查看:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol.不是那么讽刺,我们所有为网络开发的人都需要知道! (3认同)
  • 我不明白.你能举例说明回应是什么吗?结果会是什么样子? (2认同)
  • 更新了答案并提供了更多解释.那更有意义吗? (2认同)

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查询参数?)


gen*_*nry 5

请求和回应。

要了解该功能req,请尝试一下console.log(req);

  • 这没有帮助;控制台中的输出是[object Object]。 (3认同)