目录
  1. 1. Express4.x API 译文 系列文章
  2. 2. 写在前面
  3. 3. Request(请求)
    1. 3.1. Properties
      1. 3.1.1. req.app
      2. 3.1.2. req.baseUrl
      3. 3.1.3. req.body
      4. 3.1.4. req.cookies
      5. 3.1.5. req.fresh
      6. 3.1.6. req.hostname
      7. 3.1.7. req.ip
      8. 3.1.8. req.ips
      9. 3.1.9. req.orignalUrl
      10. 3.1.10. req.params
      11. 3.1.11. req.path
      12. 3.1.12. req.protocol
      13. 3.1.13. req.query
      14. 3.1.14. req.route
      15. 3.1.15. req.secure
      16. 3.1.16. req.signedCookies
      17. 3.1.17. req.stale
      18. 3.1.18. req.subdomains
      19. 3.1.19. req.xhr
    2. 3.2. Methods
      1. 3.2.1. req.accepts(types)
      2. 3.2.2. req.acceptsCharsets(charset[,…])
      3. 3.2.3. req.acceptsEncodings(encoding[,…])
      4. 3.2.4. req.acceptsLanguages[lang[,…]]
      5. 3.2.5. req.get(field)
      6. 3.2.6. req.is(type)
      7. 3.2.7. req.param(name,[,defaultValue])
  4. 4. 写在后面
Express4.x API (二):Request (译)

Express4.x API 译文 系列文章

原文地址:express.com

Request(请求)

req代表http request请求,具有请求查询字符串,参数,body,http头等等的性能。在本文件和惯例中,这个对象总是被简称为req(http response对象是res),但是它的实际名称取决于你正在工作的回调函数的参数

举个栗子:

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

当然你也可以这样:

app.get('user/"id/',function(request,response){
response.send('user ' + request.params.id);
})

Properties

在express4.x中,req.files在默认情况下是不再可以被使用的,在req.files对象为了获得upload files,使用多个处理中间件,像 busboy,formidable,multiparty,connect-multiparty或者pez

req.app

此属性持有对使用中间件的Express应用程序实例的引用

如果你按照所创建的一个模块,刚暴露一个中间件为了在你的主文件中使用它,然后中间件可以通过req.app访问Express实例

举个栗子:

// index
app.get("/viewdirectory/",require("./mymiddleware.js"))
// mymiddleware.js
module.exports = function(req,res){
res.send('The views direction is " + req.app.get('views'));
}

req.baseUrl

安装路由器的实例的URL路径

举个栗子:

var greet = express.Router();
greet.get('/jp',function(req,res){
console.log(req.baseUrl) // greet
res.send('Konichiwa!')
})

app.use('/greet',greet) // load the router on '/greet'

即使使用路径模式或一组路径模式来加载路由器,baseUrl特性返回匹配字符串,而不是模式(s),

在下面这个路径中,greet路径加载两个路由路径

app.use(['/gre+t','hel{2}o'],greet)   // load the router on '/gre+t' and '/hel{2}o'

当一个请求指向/greet/jp,req.baseUrl是’/greet’.当一个请求指向/hello/jp,req.baseUrl/hello
req.baseUrl类似于app.mountpath,除了app.mountpath返回路径匹配的模式

req.body

包含请求主体中提交数据的键值对.默认情况下,它是undefined,当时用body-parsing中间件例如body-parsermulter时被填充

下面这个栗子展示如何使用中间件来填充req.body

var app = require('express')
var bodyParser = require('body-parser')
var multer = require('multer')

app.use(bodyParser.json()); // 解析 application/json
app.use(bodyParser.urlencoded({extended:true})); // 解析 application/x-www-form-urlencoded
app.use(multer()) // 解析multipart/form-data

app.post('/',function(req,res){
console.log(req.body)
res.json(req.body)
})

req.cookies

当使用cookie-parser中间件,此属性是包含请求发送的cookie对象.如果请求不包含cookie,它默认为{}

// Cookie:name = tj
req.cookies.name // =>"tj"

req.fresh

指示是否这个请求是”fresh”,他是和req.stale相反的。这是真的如果cache-control请求头没有一个no-cache指令,下面一项都是正确的:

  • 这个if-modified-since请求头是明确指定的,last-modified请求头等于或者更早于modified响应头
  • if-none-match请求头是*
  • if-none-match请求头,在解析到他的指令之后,不匹配etag的响应头
req.fresh // => true

req.hostname

包含主机host http header的主机名

// HOST:“expample.com:3000”
req.hostname // => elample.com

req.ip

请求的远程ip地址
如果信用代理trust proxy被设置为启用,它是upstream地址

req.ip  // => 127.0.0.1

req.ips

如果信用代理trust proxy被设置为启用,此属性在X-Forwards-For请求头包含指定的ip地址数组,否者他包含一个空数组.

req.orignalUrl

req.url不是express的本身的属性,它是从节点的http模块继承来的

这个属性和req.url非常相似,然而它保留起初的url请求,允许你自由的重req.url用于内部路由的目的。举个栗子,app.use()的’mounting’特性将会重写req.url的挂载点

//  GET /serch?q=somting
req.orignalUrl // => "/serch?q=somthing"

req.params

一个包含映射到命名路由”参数”的属性对象。举个栗子,如果你有这样的路由/user:name,然后这个”name”属性可以被作为req.params.name。这个对象默认为{}

// GTE /user/tj
req.parmas.name // => "tj"

当你使用正则表达式作为路由定义时,捕获组(capture group)在数组中使用req.params[n],其中n是第n个捕获组,此规则应用于未命名通配符通配符匹配,比如/file/*

// GET /file/javascripts/jquery.js
req.params[0] // => "javascript/jquery.js"

req.path

包含request url的部分路径

// example.com/users?sort=decs
req.path // => "/users"

当从中间件调用时,挂载点不包含在req.path

req.protocol

请求协议字符串,当使用TSL请求时:http或者https。当(trust proxy)信任代理设置信任(scokets address)套接字,这个’X-Forward-Proto’的header(http,https)领域值将会被信任

req.protocol()  // => "http"

req.query

包含路由中每个查询字符串参数的属性的对象,如果没有查询字符串,它是一个空对象{}

// GET /serch?q=tobi+ferret
req.query.q // "tobi ferret"

// GET /shoes?order=decs&shoe[color]=blue&shoe[type]=converse
req.query.order // => "desc"

req.query.shoe.color // => "blue"

req.query.shoe.type // => "converse"

req.route

当前匹配的路由,字符串

举个栗子:

app.get('/user/:id?',functon userIdHandler(req,res){
console.log(req.route);
res.send('GET')
})

示例上一段代码的输出:

{
path:'user/:id?',
stack:
[
{
handle:[Function:userIdHandler],
name:'userIdHandler',
params:undefind,
path:undefind,
keys:[],
regexp:/^\/?$/i,
method:'get'
}
],
methods:{get:true}
}

req.secure

如果建立的TSL连接,则为真的布尔值,相当于

'https' == req.protocol;

req.signedCookies

当使用cookie-parser中间件时,此属性包含请求发送签署的cookie,为签名并以准备好使用,签署的cookie驻留在不同的对象中以显示开发人员的意图.否者,恶意攻击可以放置req.cookie值(这是容易欺骗的).注意签署cookie并不能使其隐藏或加密,当时简单的防止篡改(因为用于签署的secret是私有的).如果没有发送签署的cookie,则默认为{}

// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3
req.signedCookies.user // => "tobi"

req.stale

指示是否请求是stable,和它对应的是req.fresh

req.stable  // true

req.subdomains

请求的域名中的一组子域

// HOST: 'tobi.ferrets.example.com'
req.subdomains // => ["tobi","ferrets"]

req.xhr

如果请求的X-Requsested-With头域是XMLHttpRequest,布尔值为true.指示请求是由一个客户库(如jQuery)发出的

req.xhr // => true

Methods

req.accepts(types)

检查指定的内容类型是否可接受,基于请求的Accepthttp字段.该方法返回最佳匹配,或者如果没有指定内容类型是可以接受的,返回undefined(在这种情况下,应用程序回应以406Not Acceptable)

类型值可以是单个MIME类型字符串(例如’application/json’),一个扩展名例如’.json’,逗号分割的列表或者是一个数组.对于列表和数组,该方法返回最佳匹配(如果有的话)

// Accept : text/html
req.accepts('html') // => "html"

// Accept : text/*,application/json
req.accepts('html') // => "html"
req.accepts('text/html') // => 'text/html'
req.accepts(['json','text']) // => 'json'
req.accepts('application/json') // => 'application/json'

// Accepts : text/*,application/json
req.accepts('image/png');
req.accepts('png') // => undefined

// Accept: text/*;q=.5,application/json
req.accepts(['html','json']) // => json

req.acceptsCharsets(charset[,…])

基于请求的Accept-CharsetHTTP头字段,返回第一个接受指定字符集的字符集.如果指定的字符集都不接受,返回false

req.acceptsEncodings(encoding[,…])

基于请求的Accept-Encodinghttp字段,返回第一个接受的指定编码.如果指定的编码是没有接受的,返回false

req.acceptsLanguages[lang[,…]]

基于请求的Accept-Languagehttp字段,返回指定语言的第一个已接受语言.如果没有指定的语言被接受,返回fasle

req.get(field)

返回指定http请求头字段(大小写不敏感匹配),这个ReferrerReferer字段可以互换

req.get('Content-Type'); // => 'text/plain'
req.get('content-type'); // => 'text/plain'
req.get('Something') // undefined

别名req.header(field)

req.is(type)

如果传入的请求的HTTP头字段与type类型的参数指定的MIME类型匹配,返回true。否者返回false

// when content-type:text/html;charset=utf-8
req.is('html')
req.is('text/html')
req.is('text/*')
// => true

// when content-type is application/json
req.is('json')
req.is('application/json')
req.is('application/*')
// => true

req.is('html')
// => false

req.param(name,[,defaultValue])

过时的,使用req.body,req.params,req.query,如适用

返回参数名的值时

// ?name=tobi
req.param('name') // => 'tobi'

// POST name=tobi
req.param('name') // => 'tobi'

// /user/tobi for /user/:name
req.param('name') // => 'tobi'

按以下顺序执行查找,

  • req.params
  • req.body
  • req.query

直接访问req.params,req.body,req.query应该是被视为清晰可赞扬的-除非你真正接受每个对象的输入。Body-parsing必须被加载为了req.param正常的使用

写在后面

Express文档中Request部分就完成了,本人学识有限,难免有所纰漏,另外翻译仅仅是方便个人学习交流使用,无其他用意,原文地址:expressjs.com

文章作者: okaychen
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 浅笔墨画
打赏
  • 微信
  • 支付宝

评论
2