天天看點

nodejs架構Koa2探秘v1.0

nodejs架構Koa2初探

nodejs基礎(參考菜鳥教程的nodejs教程 )

  1. JavaScript文法
  2. 建立伺服器子產品http
  3. 檔案讀取子產品fs
  4. 路徑path
  5. 子產品系統 require、module.exports
  6. es6文法(新版本的nodejs除了子產品外全部支援

nodejs架構-express

文檔位址:

http://www.expressjs.com.cn/

nodejs架構-koa

中文文檔位址:

https://koa.bootcss.com/

node子產品倉庫位址:

https://www.npmjs.com/
1、初始化package.json

建立目錄koademo,執行 npm init,一路回車

2、建立一個簡單的koa應用(hello world)
安裝koa子產品 npm install koa --save
在項目根目錄建立app.js,app.js代碼如下:

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

執行node app.js
用浏覽器通路 http://localhost:3000

           
3、koa路由,使用koa-simple-router
https://www.npmjs.com/package/koa-simple-router

安裝 koa-simple-router子產品,然後修改上面的app.js代碼,變成下面這個樣子

const Koa = require('koa')
const router = require('koa-simple-router')
const app = new Koa()
 
app.use(router(_ => {
  _.get('/', (ctx, next) => {
    ctx.body = 'hello world';
  })
  _.post('/path', (ctx, next) => {
 
  })
  // 同時支援get和post請求
  _.all('/login', (ctx, next) => {
    ctx.body = {
        code: 666,
        msg: '登入成功'
    }
  })
  _.all('/regester', (ctx, next) => {
    ctx.body = {
        code: 666,
        msg: '注冊成功'
    }
  })
}))

app.listen(3000,()=>{
    console.log('服務已啟動,在 http://localhost:3000/');
});

重新開機服務,用浏覽器通路 
http://localhost:3000/login 和
http://localhost:3000/register
           

為了讓代碼結構性更好,我們可以把路由這部分單獨放在一個檔案裡

4、supervisor 伺服器自動重新開機子產品

我們發現沒修改一次代碼,都必須重新開機才能生效,這顯然不友善,supervisor子產品就可以解決這個問題

使用supervisor我們需要這樣

  1. 全局安裝supervisor npm i supervisor -g
  2. 啟動服務的時候用supervisor app.js代替node app.js
6、設定靜态目錄

在目錄中建立目錄static,在static下建立檔案demo.html,通路

http://localhost:3000/static/demo.html

是無法通路得到,因為我們還沒有設定靜态資源目錄

設定靜态資源目錄要用到koa-static子產品

安裝koa-static npm i koa-static --save

在app.j是裡加入如下代碼

const serv = require('koa-static');
app.use(serv(__dirname + '/static'));
           

再來通路

,就可以通路了

7、擷取請求參數

給剛才的demo.html添加jquery用來發送請求,然後在demo裡添加如下代碼:

var url = 'http://localhost:3000/login';
var data = {
    username: 'laohu',
    phone: '15013795539'
}
$.ajax({
    url,
    data,
    type: 'get',
    dataType: 'json',
    success: function(res) {
        console.log(res);
    },
    error: function() {
        console.log('請求失敗');
    }
})
           
  1. 擷取get請求參數

    在router.js的login接口裡加入如下代碼

// 擷取get請求參數
const username = ctx.query.username;
const phone = ctx.query.phone;
并把username和phone放入ctx.body
           

2.擷取post請求

擷取post請求需要使用koa-body子產品

安裝koa-body npm i koa-body --save

在app.js裡加入如下代碼:

const koaBody = require('koa-body');
app.use(koaBody());
           

擷取post請求參數的代碼如下

ctx.request.body.xxx
           
8、模闆

一般請求一個接口傳回的是一坨資料,然而有時候我們希望傳回的是一個html網頁或者一段html代碼(上周分享的伺服器渲染)

我們試用koa-swig子產品來向前端傳回一個html

安裝koa-swig npm i koa-swig

  • 在根目錄建立views目錄,在views目錄下建立tpl.html
  • 在app.js添加如下代碼:
const render = require('koa-swig')
const co = require('co')
app.context.render = co.wrap(render({ 
    root: './views', 
    autoescape: true,
    cache: 'memory', 
    writeBody: false, 
    ext: 'html' }))
    
// 在router.js裡面的根路由修改成下面這樣,同時給模闆傳遞變量msg
_.get('/', async (ctx, next) => {
    ctx.body = await ctx.render('tpl', { msg: 'hello' });
})
           
  • 在tpl.html裡面添加代碼:
<p>{{msg}}</p>
           
  • 通路 http://localhost:3000 ,就可以看到一個html頁面
  • 可以使用axios請求背景接口,然後渲染頁面,最後傳回給前端(詳情請看github上的demo)
9、相關位址

本文github位址:

https://github.com/wotu-courses/koa2

本文相關nodejs項目位址:

https://github.com/wotu-courses/zhihu_server.git

繼續閱讀