Express4.x API 譯文 系列文章
- Express4.x API (一):application (譯) -- 完成
- Express4.x API (二):request (譯) -- 完成
- Express4.x API (三):Response (譯) -- 完成
- Express4.x API (四):router (譯) -- 完成
最近學習express想要系統的過一遍API,www.expressjs.com是express英文官網(進入www.epxressjs.com.cn發現也是只有前幾句話是中文呀~~),所以自己准備在express學習的過程也翻譯一遍API,一是熟悉Express文檔,二是鍛煉自己英語閱讀能力.
原文地址: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-parser
和multer
時被填充
下面這個栗子展示如何使用中間件來填充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)
檢查指定的內容類型是否可接受,基於請求的Accept
http字段.該方法返回最佳匹配,或者如果沒有指定內容類型是可以接受的,返回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-Charset
HTTP頭字段,返回第一個接受指定字符集的字符集.如果指定的字符集都不接受,返回false
req.acceptsEncodings(encoding[,...])
基於請求的Accept-Encoding
http字段,返回第一個接受的指定編碼.如果指定的編碼是沒有接受的,返回false
req.acceptsLanguages[lang[,...]]
基於請求的Accept-Language
http字段,返回指定語言的第一個已接受語言.如果沒有指定的語言被接受,返回fasle
req.get(field)
返回指定http請求頭字段(大小寫不敏感匹配),這個Referrer
和Referer
字段可以互換
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