koa

koa

链接:

官网: 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
})

跨域

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

其他

【引入模板文件】
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 来抛错

koa2

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输出的一个插件。
上一篇:封装两个简单的Jquery组件


下一篇:【Android病毒分析报告】 - ZxtdPay 吸费恶魔