您好,登錄后才能下訂單哦!
Github上有一個express風格的koa腳手架,用著挺方便,一直以來使用koa開發(fā)web項目用的也都是那個腳手架,今天想自己從頭搭一個web項目,就折騰了一下
腳手架地址: https://github.com/17koa/koa-generator
初始化
使用 npm init 初始化一個nodejs項目
mkdir koa-demo cd koa-demo npm init
一直回車即可,創(chuàng)建好之后目錄里會有一個 package.json 文件
安裝依賴
npm install --save koa koa-body koa-logger koa-json-error koa-router koa-static koa-njk
配置
在根目錄下創(chuàng)建 app.js 然后貼上下面代碼,代碼內(nèi)有注釋,很簡單
// 引入依賴 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 } })); // 添加靜態(tài)資源文件映射 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 ''; } }); })); // 解析表單提交參數(shù) app.use(koa_body()); // 顯示請求和響應(yīng)日志 app.use(koa_logger()); // 路由 app.use(routers.routes()) // 程序啟動監(jiān)聽的端口 const port = 3000; app.listen(port); console.log('Listening on ' + port);
路由
在根目錄下創(chuàng)建 routes 文件夾
在 routes 文件夾內(nèi)創(chuàng)建 index.js routers.js 文件
在 index.js 文件內(nèi)添加如下代碼
// 測試路由,輸出請求的參數(shù) 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 文件內(nèi)配置路由
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
靜態(tài)文件
在根目錄創(chuàng)建文件夾 static 添加 app.css 文件,寫上下面代碼
body { background-color: #eee; }
模板
在根目錄創(chuàng)建文件夾 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" rel="external nofollow" > </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": "測試異常" }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。