轉發node
自NodeJS早期以來,Express一直是NodeJS開發人員事實上的標準Web框架。
可是,JavaScript在過去幾年中已經走過了漫長的道路,像promises和async函數這樣的功能使得構建更小,更強大的Web框架成爲可能。git
Koa就是這樣一個框架。
它由Express背後的團隊構建,以利用最新的JavaScript和NodeJS功能,特別是異步功能。github
與Express和其餘node框架(如Hapi)不一樣,Koa不須要使用回調。
這消除了難以跟蹤的錯誤的巨大潛在來源,並使框架很是容易爲新開發人員選擇。typescript
在本文中,我將向您介紹如何使用Koa和TypeScript來開發新的Web應用程序項目npm
Koa須要一個具備異步功能支持的Node版本,所以在開始以前確保安裝了Node 8.x(或更高版本)。
Node 8將於2017年10月成爲新的長期支持版本,所以它是啓動新項目的絕佳選擇。json
咱們如今將建立一個安裝瞭如下內容的新node項目:api
1. Koa
2. Koa Router
3. TypeScript
4. TS-Node 和 Nodemon(用於在開發期間自動構建和重啓)promise
爲項目建立一個新文件夾,而後執行如下命令:瀏覽器
npm init # and follow the resulting prompts to set up the project npm i koa koa-router npm i --save-dev typescript ts-node nodemon npm i --save-dev @types/koa @types/koa-router
如今,在項目的根目錄中,建立一個新的tsconfig.json文件並添加如下內容:服務器
{ "compilerOptions": { "module": "commonjs", "target": "es2017", "noImplicitAny": true, "outDir": "./dist", "sourceMap": true }, "include": [ "./src/***/*", ] }
請注意,咱們將TypeScript配置爲轉換爲ES2017 - 這可確保咱們利用Node的本機async/await功能。
因爲Koa的核心是微框架,所以啓動和運行它很是簡單。在項目目錄中,建立一個src文件夾,在其中建立一個新文件:server.ts,其中包含如下內容:
import * as Koa from 'koa'; import * as Router from "koa-router"; const app = new Koa(); const router = new Router(); router.get('/*', async (ctx) => { ctx.body = "Hi TS"; }) app.use(router.routes()); app.listen(8080); console.log("Server running on port 8080");
在開發過程當中,每次進行更改時都要記住從新啓動服務器會很麻煩,因此我想設置個人服務器端項目以自動從新啓動代碼更改。
爲此,咱們將向咱們的項目添加watch-server npm腳本。
爲此,請將如下內容添加到package.json的"scripts"部分:
"watch-server": "nodemon --watch 'src/***/*' -e ts,tsx --exec 'ts-node' ./src/server.ts"
如今開始新的TypeScript Koa項目,只需執行如下操做便可
npm run watch-server
您應該看到如下輸出:
> ts_node_koa_blog@1.0.0 watch-server /Users/durban/nodejs/ts_node_koa_blog > nodemon --watch 'src/***/*' -e ts,tsx --exec 'ts-node' ./src/server.ts [nodemon] 1.18.4 [nodemon] to restart at any time, enter `rs` [nodemon] watching: src/***/* [nodemon] starting `ts-node ./src/server.ts` Server running on port 8080
如今您應該可以在瀏覽器中訪問http//localhost:8080/ :)
主要的Koa庫只包含基本的HTTP功能。
要構建完整的Web應用程序,咱們須要添加適當的中間件,例如Logging, Error Handling, CSRF Protection等。在Koa中,中間件本質上是一堆函數,經過app.use()建立。
收到Web請求後,它將傳遞給堆棧中的第一個函數。
該函數能夠處理請求,而後可選地將其傳遞給下一個中間件函數。
讓咱們將上面的示例擴展爲包含一箇中間件函數,該函數將每一個Web請求的URL記錄到控制檯:
import * as Koa from 'koa'; import * as Router from "koa-router"; const app = new Koa(); app.use(async (ctx, next) => { // Log the request to the console console.log("Url: ", ctx.url); // Pass the request to the next middleware function await next(); }) const router = new Router(); router.get('/*', async (ctx) => { ctx.body = "Hi TS"; }) app.use(router.routes()); app.listen(8080); console.log("Server running on port 8080");
在上面的示例中,咱們如今定義兩個中間件函數:
1. 第一個中間件函數從請求上下文(ctx.url)獲取Url,並使用console.log()將其輸出到控制檯
2. 而後該函數await next(),告訴Koa將請求傳遞給堆棧中的下一個中間件函數
3. 第二個中間件函數來自koa-router - 它使用請求的url來匹配咱們經過router.get()配置的路由如今,當您在瀏覽器中訪問http://localhost:8080/時,您應該看到相似於如下內容的輸出:
> ts_node_koa_blog@1.0.0 watch-server /Users/durban/nodejs/ts_node_koa_blog > nodemon --watch 'src/***/*' -e ts,tsx --exec 'ts-node' ./src/server.ts [nodemon] 1.18.4 [nodemon] to restart at any time, enter `rs` [nodemon] watching: src/***/* [nodemon] starting `ts-node ./src/server.ts` Server running on port 8080 Url: / Url: / Url: /blog Url: /blog
顯然,你真的不想爲你的網絡應用從新發明輪子。
根據您要建立的應用程序類型,如下中間件可能頗有用:
Koa路由器
https://github.com/alexmingoia/koa-routerKoa Body Parser(用於JSON和Form Data支持)
https://github.com/dlau/koa-bodyKoa Cross-Site-Request-Forgery(CSRF)預防
https://github.com/koajs/csrfKoa Examples(許多有用的東西,包括錯誤處理)
https://github.com/koajs/examples
我已經建立了一個基本的TypeScript和Koa項目。能夠進行後面本身感興趣的開發了。