Express4.x API 譯文 系列文章
- Express4.x API (一):application (譯) -- 完成
- Express4.x API (二):request (譯) -- 完成
- Express4.x API (三):Response (譯) -- 完成
- Express4.x API (四):router (譯) -- 完成
技術庫更迭較快,很難使譯文和官方的API保持同步,更何況更多的大神看英文和中文一樣的流暢,不會花時間去翻譯--,所以我們看到express中文網更多的還是英文,我們只有提升自己的英語能力才能更快的適應庫的更新迭代,閱讀到最新資料.
所以我此次翻譯的目的,一是熟悉express文檔,二是鍛煉自己英語閱讀能力;
原文地址:express.com
Response
res
對象表示一個Express應用程序在收到HTTP請求時發送的HTTP響應(response)
在這篇文檔和慣例中,HTTP響應這個對象總是被稱為res
(HTTP請求則是req),但是它的實際名稱取決於您正在工作的回調函數的參數.
舉個栗子:
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
res.app
此屬性持有對使用中間件Express應用實例的引用
res.app
和在request對象中的req.app
屬性是完全相同的
res.headersSent
布爾屬性,表示這個app是否發送了HTTP頭進行響應
app.get('/',function(req,res){
console.log(res.headersSend); // false
res.send('ok');
console.log(res.headersSend); // true
})
res.locals
一個對象包含局部變量作用域的請求的響應,因此只能用於在request/response周期中呈現的視圖(如果有的話)。否者,此屬性與app.locals是相同的
此屬性用於公開request-level
信息,例如請求的路徑名(path name),經過身份認證的用戶(authenticated user),用戶設置(user setting)等等
app.use(function(req,res,next){
res.locals.user = req.user;
req.locals.authenticated = !req.user.anonymous;
next();
})
Methods
res.append(field[,value])
res.append在Expressv4.11.0+是支持的
將指定的值到http響應頭字段.如果header還沒有被設置,它創建具有指定值的頭文件,value
參數可以是字符串或數組
如果res.set()
在res.append()
之后的話將會重置以前設置的header頭
res.append('Link',['<http://localhost/>','<http://localhost:3000/>'])
res.append('Set-Cookie','foo=bar;path=/;HttpOnly')
res.append('Warning','199 Miscellaneous warning')
res.attachment([filename])
使用attchment
設置HTTP響應Content-Dispositon
頭字段.如果給了一個文件名filename
,然后基於擴展名通過res.type()
設置Content-Type
,並設置Content-Disposition
"fliename="參數
res.attachment();
// Content-Disposition:attachment
res.attachment('path/to/logo.png');
// Content-Disposition:attachment;filename='logo.png'
// Content-Type:image/png
res.cookie(name,value[,options])
給cookie名稱設置值,value
參數可以是一個字符串或者是對象轉化為JSON,options參數可以是具有以下屬性的對象
Property | Type | Description |
---|---|---|
domain | String | cookie的域名,默認應用程序的域名 |
expires | Date | 格林尼治時間內cookie的到期日期,如果沒有指明或設置為0,創建會話cookie |
httpOnly | Boolean | 標志cookie只能由web服務器訪問 |
maxAge | String | 在毫秒內設置相對於當前時間的方便選項 |
path | String | cookie的路徑,默認為'/' |
secure | Boolean | 標記只於https一起使用的cookie |
signed | Boolean | 指示cookie是否被簽署 |
提供帶有選項設置的HTTP
Set-Cookie``res.cookie
起作用,未指定的任何選項默認值為RFC 6265
舉個栗子:
res.cookie('name','tobi',{domain:'example.com',path:'/admin',secure:true});
res.cookie('rememberme','1',{expires:'new Dtae(Date.now() + 900000),httpOnly:true'})
maxAge
選項是以當前時間為起點以毫秒為單位設置expires
的便捷選項,下面這個栗子相當於上面例子中的第二個
res.cookie('rememberme','1',{maxAge:900000,httpOnly:true})
你可以傳遞一個對象給value
參數,然后通過bodyparser
中間件將其序列化為JSON
res.cookie('cart',{items:[1,2,3]})
res.cookie('cart',{items:[1,2,3]},{maxAge:900000})
當使用cookie-parser
中間件時,此方法還支持簽署cookie,只需要設置signed
選項為true。然后res.cookie()
將會秘密的傳遞給cookieParser(secret)
去簽署這個值
res.cookie('name','tobi',{signed:true})
然后你可以通過req.signedCookie()
訪問此值
res.clearCookie(name,[,options])
通過cookie名稱清除指定的cookie
res.cookie('rememberme','tobi',{path:'/admin'});
res.clearCookie('rememberme',{path:'/admin'})
res.download(path,[,fliename][,fn])
將路徑中文件作為附件(attachment)
傳輸.通常,瀏覽器將提示用戶下載.默認情況下,Content-Disposition
頭中"filename="參數是路徑(這通常出現在瀏覽器對話框),用filename
參數覆蓋默認值
res.download('/report-12345.pdf');
res.download('/report-12345.pdf','report.pdf');
res.download('/report-12345.pdf','report.pdf',function(err){
if(err){
// 處理錯誤,但是請記得響應可能是部分發送的
// 所以檢查`res.headerssent`
}else{
// 減量下載,等
}
})
res.end([data][,encoding])
結束響應進程,This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.(這句話翻譯過來我有些不理解,我就不再翻譯,res.end用於結束響應)
快速結束響應而無需任何數據,如果你需要對數據進行響應,取而代之的是使用諸如res.send
和res.json
res.send();
res.status(404).end();
res.format(object)
在請求對象時,在Accept
HTTP頭對象上執行content-negotiation
。他使用req.accepts
基於可接受的質量值的有序類型為請求選擇一個處理程序,如果header未指定,調用第一個回調函數.當沒有找到匹配項,服務器響應406Not Acceptable
或調用默認回調函數
當選擇回調時,將設置Content-Type
響應頭.然而你可以使用回調方法在回調中更改此值例如:res.set
或者res.type
下面這個例子當Accept
頭域設置為applocation/json
或者*/json
時,將會響應{'message':'hey'}(然而如果是"/",響應將會是'hey')
res.format({
'text/plain':function(){
res.send('hey')
},
'text/html':function(){
res.send('<p>hey</p>')
}
'applaction/json':function(){
res.send(message:'hey')
}
'default':function(){
// 記錄請求並用406響應
res.status(406).send('Not Acceptable')
}
})
除了規范化MOME類型,對於稍微不太詳細的實現你還可以使用擴展名映射到這些類型
res.format({
text:function(){
res.send('hey');
}
html:function(){
res.send('<p>hey</p>');
}
json:function(){
res.send({message:'hey'});
}
})
res.get(field)
返回由路由字段指定的http響應頭(對大小寫是不敏感的)
res.get('Content-Tpye'); // => 'text/plain'
res.json([body])
發送一個JSON響應,這個方法和res.send
是一樣的傳遞一個對象或者數組作為參數.但是你可以使用它將其他值轉化為JSON,例如null,undefined(雖然這些在技術上不是有效的JSON)
res.json(null)
res.json(user:'tobi')
res.status(500).json(error:'message')
res.jsonp([body])
發送一個JSONP支持的JSON響應,這個方法和req.json()
是相同的,除了他選擇在JSONP的回調支持
res.jsonp(null) // => null
res.jsonp({user:'tobi'}) // => {"user":"tobi"}
res.status(500).jsonp({error:'message'}) // => {"error":"message"}
以下是一些JSONP響應用相同的代碼的栗子:
// ?callback=foo
res.jsonp(user:"tobi") // => foo({"user":"tobi"})
app.set('JSONP callback name ','cb');
// ?cb=foo
res.status(500).jsonp({error:'message'}) // => foo({"error":"message"})
res.links(links)
將提供的鏈接作為參數的屬性添加到響應的Link
HTTP 頭字段
res.links({
next:'http://api.example.com/user?page=2',
last:'http://api.example.com/user?page=5'
})
產出
Link:<http://api.example.com/user?page=2>; rel='next'
:<http://api.example.com/user?page=5>; rel='last'
res.location(path)
設置響應location
HTTP頭為指定的path路徑參數
res.location('/foo/bar');
res.location('http://example.com');
res.location('back');
帶有back
參數的的路徑帶有特殊的意義,它指的是在請求的Referer
報頭指定的URL,如果沒有被指定,它指向"/"
res.redirect([status,] path)
重定向URL來自指定的路徑,使用指定的HTTP狀態碼.如果沒有指定狀態,狀態代碼默認為'302 Found'
res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301,'http://example.com');
res.redirect('../login');
重定向可以完全的將URL重定向到另一個不同的網站
res.redirect('http://google.com');
重定向可以使用相對主機的路徑,例如,如果你的應用程序是"http://example.com/admin/post/new",下面將會將它重定向到"http://example.com/admin"
res.redirect('/admin')
重定向可以相對於當前的URL,例如來自"http://example.com/blog/admin/"(注意最后的尾斜杠),下面將重定向到"http://example.com/blog/admin/post/new"
res.redirect('post/new')
如果上面admin最后沒有尾斜杠,將會重定向至"http://example.com/blog/post/new"
如果你發現上述行為令人困惑,把路徑段看做目錄(尾隨斜杠)和文件,他將開始變得有意義
相對路徑的重定向也是有可能的,如果你是"http://example.com/admin/post/new",下面將會重定向到"http://example.com/admin/post"
res.redirect('..');
一個back
重定向到請求返回referer
,如果referer
丟失默認為'/'
res.render(view[,locals][,callback])
呈現視圖並將HTML發送給客戶端,可選參數:
- locals,屬性定義視圖的局部變量的對象
- callback,回調函數,如果提供的話,返回可能的錯誤和呈現的字符串,但並不自動響應.當錯誤發生時,該方法在內部調用
next(err)
res.render('index')
res.render('index',function(err,html){
res.send(html)
})
// 將局部變量傳遞給視圖
res.render('user',{name:'tobi'},function(err,html){
// ..
})
res.send([body])
發送http響應
body
參數可以是一個buffer
對象,字符串,對象,數組.舉個栗子:
res.send(new Buffer('whoop'))
res.send({some:'json'})
res.send('<p>some html</p>')
res.status(404).send('sorry,er can not find that!')
res.status(500).send({error:'something brew up'})
當參數是一個buffer對象時,該方法設置Content-Type
響應頭字段為application/octet-stream
,除非先定義如下所示:
res.set('Content-Type':'text/html')
res.send(new Buffer('<p>some html</p>'))
當參數為字符串時,這個方法設置'Content-Type'為'text/html'
res.send('<p>some html</p>')
當參數為數組或者對象時,Express用JSON表示響應
res.send({user:'tobi'})
res.send([1,2,3])
res.sendFile(path[,options][,fn])
res.sendFile()在Express v4.8.0之前被支持
在給定路徑上傳輸文件,根據文件的擴展設置"Content-Tpye"響應HTTP頭字段.除非在選項對象中設置根選項,路徑必須是文件的絕對路徑
下表中列出了選項對象中的詳細信息
Property | Description | Default | Availability |
---|---|---|---|
maxAge | 以毫秒為單位設置max-age緩存控制頭或者MS格式的字符串 | 0 | |
root | 相關文件的根目錄 | ||
lastModified | 設置last-modified頭設置為操作系統上文件的最后修改日期,設置false禁用它 | Enabled | 4.9.0+ |
headers | 包含與文件服務對象的HTTP頭 | ||
dotfiles | 可能值為"allow","deny","ignore" | "ignore" |
該方法調用一個回調函數fn(err)
當傳輸完成或發生錯誤時.如果指定了回調函數並發生錯誤時,回調函數必須通過終止請求響應周期來顯式地處理響應過程,或者傳遞控制給下一個路由
下面這個栗子使用了res.sendFile()
的所有參數
res.send('/file/:name',function(req,res,next){
var options={
root:__dirname+'/public',
dotfiles:'deny',
headers:{
'x-timestamp':Date.now(),
'x-sent':true
}
}
var flieName = req.params.name;
res.sendFile(fileName,options,funcion(err){
if(err){
console.log(err);
res.status(err.status).end();
}else{
console.log('Sent:', fileName);
}
})
})
res.sendFile()在下面的例子中,提供對文件服務的fine-grained
支持,
app.get('/user/:uid/photos/:file',function(req,res){
var uid = req.params.uid;
var file = req.params.file;
req.user.mayViewFilesFrom(uid,function(yes){
if(yes){
res.sendFile('/uploads/' + uid + '/' + file);
}else{
res.status(403).send("sorry you cant\'s see that.")
}
})
})
res.sendStatus(statusCode)
設置響應的HTTP狀態碼並將字符串形式作為響應體發送
res.sendStatus(200); // 等於 res.status(200).send('ok')
res.sendStatus(403); // 等於 res.status(403).send('Forbidden')
res.sendStatus(404); // 等於 res.status(404).send('Not Found')
res.sendStatus(500); // 等於 res.status(500).send('Internal Server Error')
如果指定了不受支持的狀態代碼,HTTP狀態仍然設置狀態碼和代碼的字符串版本為響應正文中發送
res.sendStatus(2000) // 等於 res.status(2000).send('2000')
res.set(field [,value])
將HTTP響應頭filed設置為value值.立即設置多個字段,傳遞一個對象作為參數
res.set('Content-Type':'text/plain');
res.set({
'Content-Type':'text.plain',
'Content-Length':'123',
'ETag':'12345'
})
別名為res.header(field[,value])
res.status(code)
使用此方法為響應設置HTTP狀態,這是一個連貫性的Node response.statusCode
別名
res.status(403).send();
res.status(400).send('Bad Request');
res.status(404).sendFile('/absolute/path/to/404.png')
res.type(type)
將Content-Type
的HTTP頭設置為MIME
類型,通過mime.lookup
指定類型.如果類型包含'/'字符,設置"Content-Type"為'type'
res.type('.html') // => 'text/html'
res.type('html') // =>'text/html'
res.type('json') // => 'application/json'
res.type('application/json') // => 'application/json'
res.type('png') // => image/png:
res.vary(field)
如果它不在那里,添加字段到vary
響應頭
res.vary('User-Agent').render('docs');
寫在后面
Express文檔中Request部分就完成了,本人學識有限,難免有所紕漏,另外翻譯僅僅是方便個人學習交流使用,無其他用意,原文地址:expressjs.com