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

216
在下面的Express函数中:
app.get('/user/:id', function(req, res){
    res.send('user' + req.params.id);
});

reqres是什么?它们代表什么,意味着什么,可以做什么?

谢谢!


2
req == "request" // res == "response" - nilon
2
我也想加上我的意见,我们应该更倾向于使用params名称作为请求/响应,而不是req/res,因为只有字符差异,这可能会成为错误的原因,一旦我们的代码库增加。谢谢。 - Wasit Shafi
3个回答

321

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);
});

1
你可以使用curl命令查看包含头部信息的完整响应。 - generalhenry
4
您可能希望查看:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol。并不是在挖苦,这是我们所有为Web开发的人都需要了解的内容! - TK-421
7
是的,这很棒,应该放在 express.js 网站的主页面上。 - Anton
expressnoob - 响应对象与请求对象一样,但它包含与响应相关的字段和方法。通常使用响应的send()方法。send()接受许多不同类型的第一个参数,它成为HTTP响应正文,第二个参数是HTTP响应代码。 - grantwparks
7
如果有人想要了解reqres结构的详细信息,可以在Express文档中找到相关描述:req:http://expressjs.com/en/api.html#req, res:http://expressjs.com/en/api.html#res。 - akn
显示剩余4条评论

26
我注意到 Dave Ward 的回答中存在一个错误(也许是最近的更改?):查询字符串参数在 request.query 中,而不是 request.params。(请参见https://dev59.com/_Ww05IYBdhLWcg3w9mnd#6913287
默认情况下,request.params 中填充了路由中任何 "组件匹配" 的值。
app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

并且,如果你已经配置了express使用它的bodyparser (app.use(express.bodyParser());) 来处理POST数据. (参见 如何检索POST查询参数? )


7

请求和响应。

为了理解req,请尝试使用console.log(req);


3
这没什么帮助,控制台输出的是 [object Object]。 - J.E.C.
1
如果你想要JSON,你需要这样做: console.log(JSON.Stringify(req.body); - maridob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接