koa2初步搭建及基礎
由於最近在使用nodejs,所以對nodejs產生了濃厚的興趣,感覺JavaScript纔是未來。這篇主要記錄一些koa2項目的初步搭建及基礎知識,包括創建初始化項目,Context上下文對象, RESTClient工具使用,及Koa2中間件基礎。
1. koa初始搭建
- 先創建項目目錄,比如:koa2learn
- 用vscode打開koa2learn文件夾,在終端中鍵入初始化命令
命令分別是初始化node.js項目和本地安裝koa2。
npm init
npm install koa -save
- 目錄下新建 app.js,鍵入啓動代碼如下:
const koa = require('koa');
const app = new koa();
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello World!</h1>'
})
app.listen(3000,() => {
console.log('server is running at http://localhost:3000');
})
- 瀏覽器中輸入url返回如下
2. Context對象
Context:上下文對象,請求Request對象和響應Response對象的封裝。
2.1 ctx.request
ctx.request是Koa的請求對象,示例代碼中分別舉例說明了獲取Get請求參數,獲取Post請求參數,以及處理路由的基礎方法。
const koa = require('koa');
const app = new koa();
app.use(async (ctx, next) => {
ctx.response.type = 'text/html';
if(ctx.request.method === 'GET'){
// 路由處理
if(ctx.request.path === '/html'){
ctx.response.type = 'html';
ctx.response.body = '<h1>Hello World!</h1>';
}else{
// Get請求參數獲取方法
ctx.response.body = {
usrl: ctx.request.url,
query: ctx.request.query,
queryString: ctx.request.querystring
}
}
} else if (ctx.request.method === 'POST'){
// Post請求參數獲取方法
let postdata = '';
ctx.req.on('data', (data) => {
postdata += data;
});
ctx.req.on('end', () => {
console.log(postdata);
})
}
await next();
})
app.listen(3000,() => {
console.log('server is running at http://localhost:3000');
})
2.2 RESTClient測試
對以上代碼進行http接口測試,這裏我採用了RESTClient測試工具進行測試,因爲我嫌Postman太麻煩,簡單的測試用RESTClient就夠了。這裏列出下載地址:https://github.com/Wisdom-Projects/rest-client
- get請求測試
- post請求測試
在vscode調試控制檯裏的輸出中可以看到
- 路由請求測試
2.3 ctx.response
ctx.response是Koa的響應返回對象,其中包含很多關於響應信息的api, 例如ctx.response.status用來設置請求狀態碼,ctx.response.body用來設置返回的響應主體,ctx.response.type用來設置響應的Content-Type等…
3. koa中間件
與Java中的Spring,Csharp中的asp.net一樣,web服務端開發都有個叫中間件的概念,用來截獲請求,用以加工判斷請求流。
- 自定義打印日誌的logger中間件
const koa = require('koa');
const app = new koa();
// 自定義logger中間件
const logger = async function(ctx, next){
let stime = new Date().toISOString();
console.log(stime,ctx.method,ctx.host+ctx.url);
await next();
}
// 加載中間件
app.use(logger);
app.use(async function (ctx, next) {
ctx.body = 'Hello World!';
})
app.listen(3000,() => {
console.log('server is running at http://localhost:3000');
})
- 執行打印日誌