Express4.x API (三):Response (譯)

Express4.x API 譯文 系列文章

技術庫更迭較快,很難使譯文和官方的API保持同步,更況且更多的大神看英文和中文同樣的流暢,不會花時間去翻譯--,因此咱們看到express中文網更多的仍是英文,咱們只有提高本身的英語能力才能更快的適應庫的更新迭代,閱讀到最新資料.
因此我這次翻譯的目的,一是熟悉express文檔,二是鍛鍊本身英語閱讀能力;html

原文地址:express.comnode

Response

res對象表示一個Express應用程序在收到HTTP請求時發送的HTTP響應(response)web

在這篇文檔和慣例中,HTTP響應這個對象老是被稱爲res(HTTP請求則是req),可是它的實際名稱取決於您正在工做的回調函數的參數.express

舉個栗子:json

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

固然你也能夠這樣:api

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.sendres.json

res.send();
res.status(404).end();

res.format(object)

在請求對象時,在AcceptHTTP頭對象上執行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"})

將提供的連接做爲參數的屬性添加到響應的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)

設置響應locationHTTP頭爲指定的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')

More about HTTP Status Codes

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

相關文章
相關標籤/搜索