Express4.x API (二):Request (譯)

Express4.x API 譯文 系列文章

最近學習express想要系統的過一遍API,www.expressjs.com是express英文官網(進入www.epxressjs.com.cn發現也是隻有前幾句話是中文呀~~),因此本身準備在express學習的過程也翻譯一遍API,一是熟悉Express文檔,二是鍛鍊本身英語閱讀能力.javascript

原文地址:express.comhtml

Request(請求)

req表明http request請求,具備請求查詢字符串,參數,body,http頭等等的性能。在本文件和慣例中,這個對象老是被簡稱爲req(http response對象是res),可是它的實際名稱取決於你正在工做的回調函數的參數java

舉個栗子:jquery

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或者pezexpress

req.app

此屬性持有對使用中間件的Express應用程序實例的引用json

若是你按照所建立的一個模塊,剛暴露一箇中間件爲了在你的主文件中使用它,而後中間件能夠經過req.app訪問Express實例api

舉個栗子:數組

// 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路徑cookie

舉個栗子:

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

相關文章
相關標籤/搜索