- koa就是一種簡單好用的web框架
- require引入外部文件
- request獲取請求參數(請求(Request))
- 響應(Response)
一、基本用法
1、架設HTTP服務
-
koa架設一個HTTP服務
const Koa = require('koa'); const app = new Koa(); app.listen(3000);
``
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
2、Content對象
*Koa提供一個Context對象,表示一次對話的上下文(包括HTTP 請求和HTTP回復)。通過加工這個對象,就可以控制返回給用戶的內容。
Context.response.body屬性就是發送給用戶的內容
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.response.body = 'Hello World';
};
app.use(main);
app.listen(3000);
- main函數用來設置ctx.response.body。然后app.use方法加載main函數
- ctx.response代表HTTP Response ,同樣地ctx.request代表HTTP Request.
3、HTTP Response的類型
-
Koa默認的返回類型是text/plain,如果想返回其他類型的內容,可以利用ctx.request.accepts判斷一下,客戶端希望接受什么數據(根據HTTP Request的Accept字段),然后使用ctx.response.type指定返回類型。
const Koa = require('koa'); const app = new Koa(); const main = ctx => { if (ctx.request.accepts('xml')) { ctx.response.type = 'xml'; ctx.response.body = '<data>Hello World</data>'; } else if (ctx.request.accepts('json')) { ctx.response.type = 'json'; ctx.response.body = { data: 'Hello World' }; } else if (ctx.request.accepts('html')) { ctx.response.type = 'html'; ctx.response.body = '<p>Hello World</p>'; } else { ctx.response.type = 'text'; ctx.response.body = 'Hello World'; } }; app.use(main); app.listen(3000);
4、網頁模板
-
實際開發中,返回給用戶的網頁往往都寫成模板文件,我們可以讓Koa先讀取模板文件,然后將這個模板返回給用戶。
const fs = require('fs'); const Koa = require('koa'); const app = new Koa(); const main = ctx => { ctx.response.type = 'html'; ctx.response.body = fs.createReadStream('./demos/template.html'); } app.use (main); app.listen(3000)
兩個代碼效果是相同
const fs = require('fs');
const Koa = require('koa');
const app = new Koa();
app.use(ctx=>{
ctx.response.type = 'html';
ctx.response.body = fs.createReadStream('./demos/template.html');
})
app.listen(3000)
5、POST請求如何接收
1、獲取POST請求的步驟
- 1、解析上下文ctx中的原生node.js對象req。
- 2、將POST表單數據解析成query string-字符串。
- 將字符串轉換成JSON格式
2、ctx.request和ctx.req的區別
- ctx.request:是Koa2中的Context經過封裝的請求對象,它用起來更直觀和簡單。
- ctx.req:是content提供的node.js原生HTTP請求對象。這個雖然不那么直觀,但是可以得到更多的內容,適合我們深度編程。
3、ctx.method得到請求類型
-
Koa2中提供了ctx.method屬性,可以輕松的得到請求的類型,然后根據請求類型編寫不同的相應方法,這在工作中非常常用。
const Koa = require('koa'); const app = new Koa(); app.use(async(ctx)=>{ //當請求是get請求時,顯示表單讓用戶填寫 if(ctx.url === '/' && ctx.method === 'GET'){ let html = ` <h1>Koa2 request post demo</h1> <form method="POST" action='/'> <p>username</p> <input name="username"/> <br/> <p>age</p> <input name="age" /> <br/> <p>website</p> <input name="website" /> <button type="submit">submit</button> </form> `; ctx.body = html; //當請求是post請求時 }else if(ctx.url === '/' && ctx.method === 'POST'){ ctx.body = '接收到post請求' }else{ //其他頁面顯示404頁面 ctx.body = '<h1>404!</h1>' } }) app.listen(3000,()=>{ console.log('demo server is starting at port 3000') }) -
注意,POST必須寫成POST,post不可以(必須大寫,小寫不行)
5(2)、POST請求如何接收(2)
1.解析Node原生POST參數
-
聲明一個方法,然后用Promise對象進行解析。這里我們使用了ctx.req.on來接收事件。
function parsePostData(ctx){ return new Promise((resolve,reject)=>{ try{ let postdata = ''; ctx.req.addListener('end',function(){ resolve(postdata) }) ctx.req.on('data',(data)=>{ postdata += data; }) }catch(error){ reject(error) } }) }
2.POST字符串解析JSON對象
-
寫一個字符串封裝JSON兌現對象的方法。
function parseQueryStr(queryStr) { let queryData = {}; let queryStrList = queryStr.split('&'); console.log(queryStrList); for (let [index,queryStr] of queryStrList.entries()){ //entries() 方法返回一個數組的迭代對象,該對象包含數組的鍵值對 (key/value)。 //迭代對象中數組的索引值作為 key, 數組元素作為 value。 let itemList = queryStr.split('='); console.log(itemList); //key:value queryData[itemList[0]] = decodeURIComponent(itemList[1]); // decodeURIComponent() 函數可對 encodeURIComponent() 函數編碼的 URI 進行解碼。 } return queryData; }
全部代碼
const Koa = require('koa');
const app = new Koa();
app.use(async(ctx)=>{
//當請求是get請求時,顯示表單讓用戶填寫
if(ctx.url === '/' && ctx.method === 'GET'){
let html = `
<h1>Koa2 request post demo</h1>
<form method="POST" action='/'>
<p>username</p>
<input name="username"/> <br/>
<p>age</p>
<input name="age" /> <br/>
<p>website</p>
<input name="website" />
<button type="submit">submit</button>
</form>
`;
ctx.body = html;
//當請求是post請求時
}else if(ctx.url === '/' && ctx.method === 'POST'){
let postData = await parsePostData(ctx);
ctx.body = postData;
}else{
//其他頁面顯示404頁面
ctx.body = '<h1>404!</h1>'
}
})
function parsePostData(ctx){
return new Promise((resolve,reject)=>{
try{
let postdata = '';
ctx.req.addListener('end',function(){
let parseData = parseQueryStr(postdata)
resolve(parseData)
})
ctx.req.on('data',(data)=>{
postdata += data;
})
}catch(error){
reject(error)
}
})
}
function parseQueryStr(queryStr) {
let queryData = {};
let queryStrList = queryStr.split('&');
console.log(queryStrList);
for (let [index,queryStr] of queryStrList.entries()){
//entries() 方法返回一個數組的迭代對象,該對象包含數組的鍵值對 (key/value)。
//迭代對象中數組的索引值作為 key, 數組元素作為 value。
let itemList = queryStr.split('=');
console.log(itemList);
//key:value
queryData[itemList[0]] = decodeURIComponent(itemList[1]);
// decodeURIComponent() 函數可對 encodeURIComponent() 函數編碼的 URI 進行解碼。
}
return queryData;
}
app.listen(3000,()=>{
console.log('demo server is starting at port 3000')
})
6、get請求的接收
query和querystring區別
-
在koa2中GET請求通過request接收,但是接受的方法有兩種:query和querystring。
-
query:返回的是格式化好的參數對象。
-
querystring:返回的是請求字符串
const Koa = require('koa'); const app = new Koa(); app.use(async(ctx)=>{ let url = ctx.url; //從request中接收get請求 let request = ctx.request; let req_query = request.query; let req_querystring = request.querystring; ctx.body = { url, req_query, req_querystring } }) app.listen(3000,()=>{ console.log('[demo] server is starting at port 3000') })
2.直接從ctx中獲取get請求
-
直接在ctx中得到get請求,ctx中也分為query和querystring
const Koa = require('koa'); const app = new Koa(); app.use(async(ctx)=>{ let url = ctx.url; //從上下文中直接獲取 let ctx_query = ctx.query; let ctx_querystring = ctx.querystring; ctx.body = { url, ctx_query, ctx_querystring } }) app.listen(3000,()=>{ console.log('[demo] server is starting at port 3000') })
總結:獲得GET請求的方式有兩種,一種是從request中獲得,一種是一直從上下文中獲得。獲得的格式也有兩種:query和querystring。
二、路由
1、原生路由
-
網站一般都有多個頁面。通過ctx.request.path可以獲取用戶請求的路徑,由此實現簡單的路由
const Koa = require('koa'); const app = new Koa(); const main = ctx => { if (ctx.request.path !== '/') { ctx.response.type = 'html'; ctx.response.body = '<a href="/">Index Page</a>'; } else { ctx.response.body = 'Hello World'; } }; app.use(main); app.listen(3000);
2、koa-route模塊
-
原生路由用起來不太方便,我們可以使用封裝好的koa-route模塊
const Koa = require('koa'); const route = require('koa-route'); const app = new Koa(); const about = ctx =>{ ctx.response.type = 'html'; ctx.response.body = '<a href="/">Index Page</a>' }; const main = ctx =>{ ctx.response.body = 'Hello World' } app.use(route.get('/',main)); app.use(route.get('/about',about)) app.listen(3000); -
根路徑
/的處理函數是main,/about路徑的處理函數是about
3、靜態資源
-
如果網站提供靜態資源(圖片、字體、樣式、腳本......),為它們一個個寫路由就很麻煩,也沒必要。koa-static模塊封裝了這部分的請求。
const Koa = require('koa'); const app = new Koa(); const path = require('path'); const serve = require('koa-static'); const main = serve(path.join(__dirname)); app.use(main); app.listen(3000);
1、安裝koa-static
- npm install --save koa-static
2、新建static文件夾
- 在static文件夾中讓人圖片、css和js文件
3、使用koa-static中間件
const Koa = require('koa');
const path = require('path');
const static = require('koa-static');
const app = new Koa();
const staticPath = './static';
app.use(static(path.join(__dirname,staticPath)));
app.use(async(ctx)=>{
ctx.body = 'hello static'
})
app.listen(3000,()=>{
console.log('demo server is starting at port 3000')
})
4、重定向
-
有些場合,服務器需要重定向(redirect)訪問請求。比如,用戶登錄以后,將他重定向到登錄前的頁面。ctx.response.redirect()方法可以發出一個302跳轉,將用戶導向另一個路由
const Koa = require('koa'); const route = require('koa-route'); const app = new Koa(); const redirect = ctx => { ctx.response.redirect('/'); }; const main = ctx => { ctx.response.body = 'Hello World'; }; app.use(route.get('/', main)); app.use(route.get('/redirect', redirect)); app.listen(3000);
訪問 http://127.0.0.1:3000/redirect ,瀏覽器會將用戶導向根路由。
5、ctx.request.url
-
要想實現原生路由,需要得到地址欄輸入的路徑,然后根據路徑的不同進行跳轉。用ctx.request.url就可以實現
const Koa = require('koa') const app = new Koa() app.use( async ( ctx ) => { let url = ctx.request.url ctx.body = url }) app.listen(3000)
三、中間件
1、Logger功能
-
Koa的最大特色,也是最重要的一個設計,就是中間件(middleware)
const Koa = require('koa'); const app = new Koa(); const main = ctx => { console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`); ctx.response.body = 'Hello World'; }; app.use(main); app.listen(3000); -
訪問 http://127.0.0.1:3000 ,命令行就會輸出日志。
-
1534751382271 GET /
2、上一個例子里面的Logger功能,可以拆分成一個獨立函數
const Koa = require('koa');
const app = new Koa();
const logger = (ctx,next)=>{
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
next();
}
const main = ctx =>{
ctx.response.body = '我是中間件'
}
app.use(logger);
app.use(main);
app.listen(3000);
- 像上面代碼中的logger函數就叫做'中間件'(middleware),因為它處在HTTP Request和HTTP Response中間,用來實現某種中間功能。app.use()用來加載中間件。
- 基本上,Koa所有的功能都是通過中間件實現的,前面例子里面的main也是中間件。每個中間件默認接受兩個參數,第一個參數是Context對象,第一個參數是next函數。只要調用next函數,就可以把執行權轉交給下一個中間件。
3、中間件棧
-
多個中間件會形成一個棧結構(middle stack),以'先進后出'(first-in-last-out)的順序執行
1. 最外層的中間件首先執行。 2. 調用next函數,把執行權交給下一個中間件。 3. ... 4. 最內層的中間件最后執行。 5. 執行結束后,把執行權交回上一層的中間件。 6. ... 7. 最外層的中間件收回執行權之后,執行next函數后面的代碼。
``
const Koa = require('koa');
const app = new Koa();
const one = (ctx, next) => {
console.log('>> one');
next();
console.log('<< one');
}
const two = (ctx, next) => {
console.log('>> two');
next();
console.log('<< two');
}
const three = (ctx, next) => {
console.log('>> three');
next();
console.log('<< three');
}
app.use(one);
app.use(two);
app.use(three);
app.listen(3000);
- 如果中間件內部調用next函數,那么執行權就不會傳遞下去
4、異步中間件
-
迄今為止,所有例子的中間件都是同步的,不包含異步操作。如果有異步操作(比如讀取數據庫),中間件就必須寫成async函數
const fs = require('fs.promised'); const Koa = require('koa'); const app = new Koa(); const main = async function(ctx,next){ ctx.response.type = 'html'; ctx.response.body = await fs.readFile('./demos/template.html','utf-8') } app.use(main); app.listen(3000); -
fs.readFile是一個異步操作,必須寫成await fs.readFile(),然后中間件必須寫成async函數
5、中間件的合成
-
koa-compose模塊可以將多個中間件合成為一個
const Koa = require('koa'); const compose = require('koa-compose'); const app = new Koa(); const logger = (ctx,next) =>{ console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`); next(); } const main = ctx=>{ ctx.response.body = 'hello world2' } const middlewares = compose([logger,main]) app.use(middlewares); app.listen(3000);
6、koa-bodyparser中間件
- 對於POST請求的處理,koa-bodyparser中間件可以把koa2上下文的formData數據解析到ctx.request.body中
1、安裝中間件
- 使用npm進行安裝,需要注意的是我們這里要用–save,因為它在生產環境中需要使用。
- npm install --save koa-bodyparser@3
2、引入使用
-
安裝完成后,需要在代碼中引入並使用。我們在代碼頂部用require進行引入。
-
const bodyParser = require('koa-bodyparser');
-
然后進行使用,如果不使用是沒辦法調用的,使用代碼如下。
-
app.use(bodyParser());
-
在代碼中使用后,直接可以用ctx.request.body進行獲取POST請求參數,中間件自動給我們作了解析。
const Koa = require('koa'); const app = new Koa(); const bodyParser = require('koa-bodyparser'); app.use(bodyParser()) app.use(async(ctx)=>{ //當請求是get請求時,顯示表單讓用戶填寫 if(ctx.url === '/' && ctx.method === 'GET'){ let html = ` <h1>Koa2 request post demo</h1> <form method="POST" action='/'> <p>username</p> <input name="username"/> <br/> <p>age</p> <input name="age" /> <br/> <p>website</p> <input name="website" /> <button type="submit">submit</button> </form> `; ctx.body = html; //當請求是post請求時 }else if(ctx.url === '/' && ctx.method === 'POST'){ let postData = ctx.request.body; ctx.body = postData; }else{ //其他頁面顯示404頁面 ctx.body = '<h1>404!</h1>' } }) app.listen(3000,()=>{ console.log('demo server is starting at port 3000') })
四、錯誤處理
1、500錯誤
-
如果代碼運行過程中發生錯誤,我們需要吧錯誤信息返回給用戶。HTTP協定約定這時要返回500狀態碼。Koa提供了ctx.throw()方法,用來拋出錯誤,ctx.throw(500)錯誤。
const Koa = require('koa'); const app = new Koa(); const main = ctx => { ctx.throw(500); }; app.use(main); app.listen(3000);
2、404錯誤
-
如果將ctx.response.status設置成404,就相當於ctx.throw(404),返回404錯誤
const Koa = require('koa'); const app = new Koa(); const main = ctx => { ctx.response.status = 404; ctx.response.body = 'Page Not Found--404' } app.use(main); app.listen(3000);
3、處理錯誤的中間件
-
為了方便處理錯誤,最好使用try...catch將其捕獲。但是,為每個中間件都寫try...catch太麻煩,我們可以讓最外層的中間件,負責所有中間件的錯誤處理
const Koa = require('koa'); const app = new Koa(); const handler = async (ctx, next) => { try { await next(); }catch (err){ ctx.response.status = err.statusCode || err.status || 500; ctx.response.body = { message: err.message }; } }; const main = ctx =>{ ctx.throw(500); } app.use(handler); app.use(main); app.listen(3000);
4、error事件的監聽
-
運行過程中一旦出錯,Koa會觸發一個error事件。監聽這個事件,也可以處理錯誤
const Koa = require('koa'); const app = new Koa(); const main = ctx => { ctx.throw(500); }; app.on('error', (err, ctx) => { console.error('server error', err); }); app.use(main); app.listen(3000);
5、釋放error事件
-
需要注意的是,如果被try...catch捕獲,就不會觸發error事件。這時,必須調用ctx.app.emit(),手動釋放error事件,才能讓監聽函數生效。
const Koa = require('koa'); const app = new Koa(); const handler = async (ctx,next) => { try { await next(); }catch (err) { ctx.response.status = err.statusCode || err.status || 500; ctx.response.type = 'html'; ctx.response.body = '<p>Something wrong,please contact administrator</p>'; ctx.app.emit('error',err,ctx); } } const main = ctx =>{ ctx.throw(500); } app.on('error',function(err){ console.log('logging error',err.message); console.log(err) }) app.use(handler); app.use(main); app.listen(3000); -
main函數拋出錯誤,被handler函數捕獲。catch代碼塊里面使用ctx.app.emit()手動釋放error事件,才能讓監聽函數監聽到
五、Web App的功能
1、Cookies
-
ctx.cookies 用來讀寫Cookie
const Koa = require('koa'); const app = new Koa(); const main = function(ctx){ const n = Number(ctx.cookies.get('view') || 0)+1; ctx.cookies.set('view',n); ctx.response.body = n + 'views'; } app.use(main); app.listen(3000); -
ctx.cookies.get(name,[options]) 讀取上下文請求中的cookie
-
ctx.cookies.set(name,value,[options]) 在上下文中寫入cookie
cookie 選項
- domain : 寫入cookie所在的域名
- path : 寫入cookie所在的路徑
- maxAge: cookie最大有效時長
- expires: cookie失效時間
- httpOnly: 是否只用http請求中獲得
- overwirte: 是否允許重寫
例子
const Koa = require('koa');
const app = new Koa();
app.use(async(ctx)=>{
if (ctx.url === '/index'){
ctx.cookies.set(
'myName', 'xiaoLiLi',{
domain: '127.0.0.1', //寫cookie所在的域名
path: '/index', //寫cookie所在的路徑
maxAge: 1000*60*60*24, //cookie有效時長(一天)
expires: new Date('2018-12-28'), //cookie失效時間
httpOnly: false, //是否只用於http請求中獲取
overwrite: false //是否允許重寫
}
)
ctx.body = 'cookie is OK'
}else{
if(ctx.cookies.get('myName')){
ctx.body = ctx.cookies.get('myName');
}else{
ctx.body = 'cookie is none';
}
}
})
app.listen(3000,()=>{
console.log('demo server is starting at port 3000');
})
2、表單
-
Web應用離不開處理表單。本質上,表單就是POST方法發送到服務器的鍵值對。koa-body模塊可以用來從POST請求的數據體里面提取鍵值對。
const Koa = require('koa'); const koaBody = require('koa-body'); const app = new Koa(); const main = async function(ctx) { const body = ctx.request.body; if(!body.name) ctx.throw(400,'.name required'); ctx.body = {name: body.name}; } app.use(koaBody()); app.use(main); app.listen(3000);
3、文件上傳
-
koa-body 模塊還可以用來處理文件上傳
const os = require('os'); const path = require('path'); const Koa = require('koa'); const fs = require('fs'); const koaBody = require('koa-body'); const app = new Koa(); const main = async function(ctx) { const tmpdir = os.tmpdir(); const filePaths = []; const files = ctx.request.body.files || {}; for (let key in files) { const file = files[key]; const filePath = path.join(tmpdir, file.name); const reader = fs.createReadStream(file.path); const writer = fs.createWriteStream(filePath); reader.pipe(writer); filePaths.push(filePath); } ctx.body = filePaths; }; app.use(koaBody({ multipart: true })); app.use(main); app.listen(3000); -
打開另一個命令行窗口,運行下面的命令,上傳一個文件。注意,/path/to/file要更換為真實的文件路徑。
koa2的模板初始(ejs)
安裝中間件
- npm install --save koa-views
安裝ejs模板引擎
- npm install --save ejs
編寫模板
-
新建view/index.ejs
<!DOCTYPE html> <html> <head> <title><%= title %></title>http://jspang.com/wp-admin/post.php?post=2760&action=edit# </head> <body> <h1><%= title %></h1> <p>EJS Welcome to <%= title %></p> </body> </html>
編寫koa文件
const Koa = require('koa');
const views = require('koa-views');
const path = require('path');
const app = new Koa();
//加載模板引擎
app.use(views(path.join(__dirname,'./view'),{
extension: 'ejs'
}))
app.use(async(ctx)=>{
let title = 'hello koa2';
await ctx.render('index',{
title
})
})
app.listen(3000,()=>{
console.log('demo server is starting at port 3000')
})
request 請求
1、Request別名
- ctx.header
- ctx.headers
- ctx.method
- ctx.method=
- ctx.url
- ctx.url=
- ctx.originalUrl
- ctx.origin
- ctx.href
- ctx.path
- ctx.path=
- ctx.query
- ctx.query=
- ctx.querystring
- ctx.querystring=
- ctx.host
- ctx.hostname
- ctx.fresh
- ctx.stale
- ctx.socket
- ctx.protocal
- ctx.secure
- ctx.ip
- ctx.ips
- ctx.subdomains
- ctx.is()
- ctx.accepts()
- ctx.acceptsEncodings()
- ctx.acceptsCharsets()
- ctx.acceptsLanguages()
- ctx.get()
query和querystring區別
-
在koa2中GET請求通過request接收,但是接受的方法有兩種:query和querystring。
-
query:返回的是格式化好的參數對象。
-
querystring:返回的是請求字符串。
2、Response 別名
- ctx.body
- ctx.body=
- ctx.status
- ctx.status=
- ctx.message
- ctx.message=
- ctx.length=
- ctx.length
- ctx.type=
- ctx.type
- ctx.headerSent
- ctx.redirect()
- ctx.attachment()
- ctx.set()
- ctx.append()
- ctx.remove()
- ctx.lastModeified=
- ctx.etag=
六、響應(Response)
- Koa Response 對象是在node的vanilla響應對象之上的抽象,提供諸多多HTTP服務器開發有用的功能
API
1、response.header
- 響應標頭對象
2、response.headers
- 響應標頭對象。別名是response.header
3、response.socket
- 請求套接字
4、response.status
- 獲取響應狀態。默認情況下,response.status設置為404而不是像node的res.statusCode那樣默認為200.
5、response.status =
通過數組代碼設置響應狀態
- 100 "continue"
- 101 "switching protocols"
- 102 "processing"
- 200 "ok"
- 201 "created"
- 202 "accepted"
- 203 "non-authoritative information"
- 204 "no content"
- 205 "reset content"
- 206 "partial content"
- 207 "multi-status"
- 208 "already reported"
- 226 "im used"
- 300 "multiple choices"
- 301 "moved permanently"
- 302 "found"
- 303 "see other"
- 304 "not modified"
- 305 "use proxy"
- 307 "temporary redirect"
- 308 "permanent redirect"
- 400 "bad request"
- 401 "unauthorized"
- 402 "payment required"
- 403 "forbidden"
- 404 "not found"
- 405 "method not allowed"
- 406 "not acceptable"
- 407 "proxy authentication required"
- 408 "request timeout"
- 409 "conflict"
- 410 "gone"
- 411 "length required"
- 412 "precondition failed"
- 413 "payload too large"
- 414 "uri too long"
- 415 "unsupported media type"
- 416 "range not satisfiable"
- 417 "expectation failed"
- 418 "I'm a teapot"
- 422 "unprocessable entity"
- 423 "locked"
- 424 "failed dependency"
- 426 "upgrade required"
- 428 "precondition required"
- 429 "too many requests"
- 431 "request header fields too large"
- 500 "internal server error"
- 501 "not implemented"
- 502 "bad gateway"
- 503 "service unavailable"
- 504 "gateway timeout"
- 505 "http version not supported"
- 506 "variant also negotiates"
- 507 "insufficient storage"
- 508 "loop detected"
- 510 "not extended"
- 511 "network authentication required"
6、response.message
- 獲取響應的狀態信息。默認情況下,response.message與response.status關聯。
7、response.message=
- 將響應的狀態信息設置為給定值
8、response.length=
- 將響應的Content-Length設置為給定值
9、response.length
- 以數字返回相應的Content-Length,或者從ctx.body推導出來,或者undefined。
10、response.body
- 獲取響應主體
11、response.body=
將響應體設置為以下之一:
- string 寫入
- Buffer 寫入
- Stream 管道
- Object || Array JSON-字符串化
- null 無內容響應
- 如果response.status未被設置,koa將會自動設置狀態為200或204
(1)、String
- Content-Type默認為text/html或text/plain,同時默認字符串是utf-8。Content-Length字段也是如此
(2)、Buffer
- Content-type默認為application/octet-stream,並且Content-Length字段也是如此
(3)、Stream
- Content-Type 默認為application/octet-stream
(4)、Object
- Content-Type默認為application/json。這包括普通的對象{foo:'bar'}和數組['foo','bar']
12、response.get(field)
- 不區分大小寫獲取響應頭字段值field
const etag = ctx.response.get(ETag);
13、response.set(field,value)
-
設置響應頭field到value
ctx.set('Cache-Control','no-cache')
14、response.append(field,value)
-
用值val附加額外的標頭field
ctx.append('Link', '<http://127.0.0.1/>');
15、response.set(fields)
-
用一個對象設置多個響應標頭fields:
ctx.set({ 'Etag': '1234', 'Last-Modified': date });
16、response.remove(field)
- 刪除標頭field
17、response.type
-
獲取響應Content-Type不含參數'charset'
const ct = ctx.type;
18、response.type=
-
設置響應Content-Type通過mime字符串或文件擴展名
ctx.type = 'text/plain; charset=utf-8'; ctx.type = 'image/png'; ctx.type = '.png'; ctx.type = 'png'; -
注意: 在適當的情況下為你選擇 charset, 比如 response.type = 'html' 將默認是 "utf-8". 如果你想覆蓋 charset, 使用 ctx.set('Content-Type', 'text/html') 將響應頭字段設置為直接值。
19、response.is(types...)
-
非常類似 ctx.request.is(). 檢查響應類型是否是所提供的類型之一。這對於創建操縱響應的中間件特別有用。
-
例如, 這是一個中間件,可以削減除流之外的所有HTML響應。
const minify = require('html-minifier'); app.use(async (ctx, next) => { await next(); if (!ctx.response.is('html')) return; let body = ctx.body; if (!body || body.pipe) return; if (Buffer.isBuffer(body)) body = body.toString(); ctx.body = minify(body); });
20、response.redirect(url, [alt])
-
執行 [302] 重定向到 url.
-
字符串 “back” 是特別提供Referrer支持的,當Referrer不存在時,使用 alt 或“/”。
ctx.redirect('back'); ctx.redirect('back', '/index.html'); ctx.redirect('/login'); ctx.redirect('http://google.com'); -
要更改 “302” 的默認狀態,只需在該調用之前或之后分配狀態。要變更主體請在此調用之后:
ctx.status = 301; ctx.redirect('/cart'); ctx.body = 'Redirecting to shopping cart';
21、response.attachment([filename])
- 將 Content-Disposition 設置為 “附件” 以指示客戶端提示下載。(可選)指定下載的 filename。
22、response.headerSent
- 檢查是否已經發送了一個響應頭。 用於查看客戶端是否可能會收到錯誤通知。
23、response.lastModified
- 將 Last-Modified 標頭返回為 Date, 如果存在。
24、response.lastModified=
-
將 Last-Modified 標頭設置為適當的 UTC 字符串。您可以將其設置為 Date 或日期字符串。
ctx.response.lastModified = new Date();
25、response.etag=
-
設置包含 " 包裹的 ETag 響應, 請注意,沒有相應的 response.etag getter。
ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');
26、response.vary(field)
- 在 field 上變化。
27、response.flushHeaders()
- 刷新任何設置的標頭,並開始主體。
