koa

koacss

連接:html

官網: https://koa.bootcss.com/#
入門: http://www.ruanyifeng.com/blog/2017/08/koa.html
進階: https://chenshenhai.github.io/koa2-note/
跨域: https://github.com/zadzbw/koa2-cors
koa 須要 node v7.6.0以上
npm i koa 
koa 2.5.0
入門
const Koa = require('koa');
const app = new Koa();

const main = ctx => {
  ctx.response.body = 'Hello World';
};

app.use(main);
app.listen(3000);
koa-generator  生成 koa項目
npm i koa-generator -g 
koa2 test
cd test && npm i 

koa2 獲取後端接口,提供給前端使用前端

router.get('/string', async (ctx, next) => {
  let a = await axios.get('http://localhost:1111/comments')  // 獲取後端接口
  console.log('a',a);
  let obj = {
    'name': 'kang',
    'age': 24
  }
  ctx.body = a.data   // 提供給前端訪問     http://xxx:3000/string
})

跨域node

const cors = require('koa2-cors')   // 提供接口給前端,解決跨域
app.use(cors())  // 跨域

 其餘ios

【引入模板文件】
const fs = require('fs');
  ctx.response.body = fs.createReadStream('./template.html');
  
【原生路由: url請求判斷    】
if (ctx.request.path !== '/') {
    ctx.response.type = 'html';
    ctx.response.body = '<a href="/">Index Page</a>';
  }  

【koa-route 路由】  
const Koa = require('koa');
const route = require('koa-route');
const app = new Koa();

const about = ctx => {
  ctx.response.type = 'html';
  ctx.response.body = '<a href="/">Index Page</a>';
};

const main = ctx => {
  ctx.response.body = 'Hello World';
};

app.use(route.get('/', main));
app.use(route.get('/about', about));

app.listen(3000);
  
const serve = require('koa-static');  // 靜態資源 
  ctx.response.redirect()   // 重定向
  

【logger 日誌中間件  】
const logger = (ctx, next) => {
  console.log(`${Date.now()}  ${ctx.request.url}`);
  next();  // 有next() 纔會繼續往下執行
}

const main = ctx => {
  ctx.response.body = 'Hello World';
};

app.use(logger);
app.use(main);  // 有next()這裏纔會執行
app.listen(3000);  

多箇中間件會造成一個棧結構(middle stack),以"先進後出"(first-in-last-out)的順序執行


// 異步中間件 必須  async 和 await 
const fs = require('fs.promised');

const main = async function (ctx, next) {
  ctx.response.type = 'html';
  ctx.response.body = await fs.readFile('./template.html', 'utf8');   【讀文件】
};

const compose = require('koa-compose');  【中間件合併】
compose([logger,main])

ctx.throw(500) 拋錯
ctx.response.status = 404;  // 經過改status 來拋錯 
View Code

 koa2git

koa2

const Koa = require('koa')
const app = new Koa()
const bodyparser = require('koa-bodyparser')    // bodyparser  不知道效果
const logger = require('koa-logger')            //  logger     不知道效果
const cors = require('koa2-cors')               // cors
const bouncer =require('koa-bouncer')     // koa-bouncer   擴展router 裏面的 ctx 方法  詳見 npm 

bodyparser()     獲取 post傳遞的表單數據、json數據,上傳文件等,使用 this.body() 獲取

app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
可不配置:  
 app
    .use(cors())
    .use(bodyparser())
    .use(logger())
    .use(bouncer.middleware())    // extends the Koa context with some methods
    .use(require('koa-static')(__dirname + '/public'))    // 靜態資源 
koa-logger  替換console.log輸出的一個插件。
View Code
相關文章
相關標籤/搜索