介绍
简称请求
,req 对象是 ‘请求’和 ‘响应’周期的一半,用于审查客户端的呼叫,执行 HTTP 请求,并在字符串或 JSON 对象中处理输入数据。
在本文中,您将了解Express中的req
对象。
前提条件
要跟随这篇文章,你将需要:
要了解更多关于 Node.js 的信息,请参阅我们的 如何在 Node.js 中编码系列
- 对 HTTP 请求的一般知识。
客户端数据管理
快递服务器通过req
对象在三个实例中从客户端接收数据:req.params
,req.query
和req.body
对象。
req.params
对象根据 URL 中指定的参数捕获数据. 在您的 index.js
文件中,执行一个具有 '/:userid’ 参数的
GET` 请求:
1[label index.js]
2// GET https://example.com/user/1
3
4app.get('/:userid', (req, res) => {
5 console.log(req.params.userid) // "1"
6})
req.params
对象告诉Express通过参数'/:userid
输出用户ID的结果,在这里,GET
请求到https://example.com/user/1
和指定参数登录到控制台中的1
的ID。
若要访问 URL 查询字符串,请将req.query
对象应用到搜索、过滤和对数据进行排序。
1[label index.js]
2// GET https://example.com/search?keyword=great-white
3
4app.get('/search', (req, res) => {
5 console.log(req.query.keyword) // "great-white"
6})
使用req.query
对象来匹配从客户端加载的数据,在一个查询条件下。在这种情况下,向req.query
路径的GET
请求告知Express在搜索查询中的关键字匹配到https://example.com
。
req.body
对象允许您从客户端访问字符串或 JSON 对象中的数据. 您通常使用req.body
对象通过 Express 服务器中的POST
和PUT
请求接收数据。
在index.js
文件中,将POST
请求设置为'/login
路线:
1// POST https://example.com/login
2//
3// {
4// "email": "[email protected]",
5// "password": "helloworld"
6// }
7
8app.post('/login', (req, res) => {
9 console.log(req.body.email) // "[email protected]"
10 console.log(req.body.password) // "helloworld"
11})
当用户在客户端输入其电子邮件和密码时,req.body
对象会存储该信息并将其发送到您的 Express 服务器。
现在你已经研究了实现req
对象的方法,让我们看看其他方法来整合到 Express 服务器中。
使用req
属性检查 URL
req
对象上的属性还可以根据解剖学返回 URL 的部分,包括protocol
,hostname
,path
,originalUrl
和subdomains
。
在index.js
文件中,将GET
请求设置为Creatures
路径:
1[label index.js]
2// https://ocean.example.com/creatures?filter=sharks
3
4app.get('/creatures', (req, res) => {
5 console.log(req.protocol) // "https"
6 console.log(req.hostname) // "example.com"
7 console.log(req.path) // "/creatures"
8 console.log(req.originalUrl) // "/creatures?filter=sharks"
9 console.log(req.subdomains) // "['ocean']"
10})
您可以使用内置的属性访问 URL 中的不同部分,例如 .protocol
和 .hostname
. 将 req
对象记录在每个属性中,会导致 URL 的解剖。
分析额外的req
属性
res
对象由属性组成,以最大限度地调用 HTTP 请求。
要访问 HTTP 方法,无论是GET
,POST
,PUT
还是DELETE
,请将.method 属性用于您的 req
对象。
1[label index.js]
2app.delete('/', (req, res) => {
3 console.log(req.method) // "DELETE"
4})
「.method」属性返回当前的 HTTP 请求方法. 在这种情况下,控制台会登录一个「DELETE」方法。
对于发送到您的服务器的标题,请将方法 .header()
附加到您的 req
对象中。
1[label index.js]
2app.post('/login', (req, res) => {
3 req.header('Content-Type') // "application/json"
4 req.header('user-agent') // "Mozilla/5.0 (Macintosh Intel Mac OS X 10_8_5) AppleWebKi..."
5 req.header('Authorization') // "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
6})
「req.header()」方法会返回标题类型,如「内容类型」和「授权」等。 对「req.header()」的参数不敏感,因此可以互换使用「req.header('Content-Type')」和「req.header('content-type')」。
如果您已在您的 Express 服务器中添加了 cookie-parser
作为依赖性,则 req.cookies
属性将存储来自您的 parser 的值。
1[label index.js]
2// Cookie sessionDate=2019-05-28T01:49:11.968Z
3
4req.cookies.sessionDate // "2019-05-28T01:49:11.968Z"
注意从req
对象调用时从cookie的会话日期返回的结果。
结论
Express 提供了内置的属性,用于使用req
对象作为请求
循环的一部分,以处理客户端的 HTTP 请求和数据。