使用koa2建立web專案
Github上有一個express風格的koa腳手架,用著挺方便,一直以來使用koa開發web專案用的也都是那個腳手架,今天想自己從頭搭一個web專案,就折騰了一下
腳手架地址: https://github.com/17koa/koa-generator
初始化
使用 npm init
初始化一個nodejs專案
mkdir koa-demo cd koa-demo npm init
一直回車即可,建立好之後目錄裡會有一個 package.json
檔案
安裝依賴
npm install --save koa koa-body koa-logger koa-json-error koa-router koa-static koa-njk
- koa
- koa-body 解析http請求引數的,支援
multipart/form-data
application/x-www-urlencoded
application/json
三種引數型別 - koa-logger 顯示http請求的日誌
- koa-router 路由
- koa-json-error 程式出異常輸出json
- koa-static 對映靜態資原始檔
- koa-njk nunjucks模板解析
原鏈文接: https://tomoya92.github.io/2019/03/11/creat-web-with-koa2/
配置
在根目錄下建立 app.js
然後貼上下面程式碼,程式碼內有註釋,很簡單
// 引入依賴 const koa = require('koa'); const koa_body = require('koa-body'); const koa_json_error = require('koa-json-error'); const koa_logger = require('koa-logger'); const koa_static = require('koa-static'); const koa_njk = require('koa-njk'); const path = require('path'); // 初始化koa const app = new koa() // 引入路由配置檔案,這個在下面說明 const routers = require('./routes/routers'); // 配置程式異常輸出的json格式 app.use(koa_json_error((err) => { return { code: err.status || 500, description: err.message } })); // 新增靜態資原始檔對映 app.use(koa_static(path.join(__dirname, 'static'))) // 新增nunjucks模板 app.use(koa_njk(path.join(__dirname, 'views'), '.njk', { autoescape: true, }, env => { // 新增自己的過濾器 env.addFilter('split', (str, comma) => { if (str) { return str.split(comma); } else { return ''; } }); })); // 解析表單提交引數 app.use(koa_body()); // 顯示請求和響應日誌 app.use(koa_logger()); // 路由 app.use(routers.routes()) // 程式啟動監聽的埠 const port = 3000; app.listen(port); console.log('Listening on ' + port);
路由
在根目錄下建立 routes
資料夾
在 routes
資料夾內建立 index.js
routers.js
檔案
在 index.js
檔案內新增如下程式碼
// 測試路由,輸出請求的引數 exports.index = async ctx => { const body = ctx.request.body; const query = ctx.request.query; const params = ctx.params; ctx.body = { body: body, query: query, params: params, }; } // 測試nunjucks模板 exports.view = async ctx => { await ctx.render('index', { title: 'Koa' }) } // 測試異常 exports.test_error = async ctx => { throw new Error('測試異常'); }
配置路由,在 routers.js
檔案內配置路由
const router = require('koa-router')(); // route const index = require('./index'); router.get('/view', index.view); router.get('/index', index.index); router.get('/index:id', index.index); router.post('/index', index.index); router.get('/test_error', index.test_error); module.exports = router
鏈原文接: https://tomoya92.github.io/2019/03/11/creat-web-with-koa2/
靜態檔案
在根目錄建立資料夾 static
新增 app.css
檔案,寫上下面程式碼
body { background-color: #eee; }
模板
在根目錄建立資料夾 views
新增 index.njk
檔案,寫上下面程式碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> <link rel="stylesheet" href="/app.css"> </head> <body> Hello, ! <br> <ul> <!-- 使用自定義的過濾器 --> </ul> </body> </html>
啟動
安裝 nodemon
npm install -g nodemon
在根目錄執行命令啟動專案
nodemon app.js
測試
訪問 http://localhost:3000/view/
訪問 http://localhost:3000/index/
可以看到輸出的json
{ "body": {}, "query": {}, "params": {} }
訪問 http://localhost:3000/index/?id=1
{ "body": {}, "query": { "id": "1" }, "params": {} }
訪問 http://localhost:3000/index/1
{ "body": {}, "query": {}, "params": { "id": "1" } }
POST 請求 curl -X POST http://localhost:3000/index/ -d '{"id": "1"}' -H 'Content-Type:application/json'
{ "body":{ "id":"1" }, "query":{}, "params":{} }
訪問 http://localhost:3000/test_error
{ "code": 500, "description": "測試異常" }
總結
寫部落格不易,轉載請保留原文連結,謝謝!
原文連結: