官网文档
cnpm i --save-dev koa2 koa-router koa-body koa-static request
npm install --save koa2
const koa2 = require('koa2');
const Router = require('koa-router');
const router = new Router();
const app = new koa2();
const Index = router.get('/', async (ctx, next) =>{
await next();
ctx.status = 200;
ctx.type= 'html';
ctx.body = "<h1>hello</h1>"
}).routes();
app.use(Index);
app.listen(1995);
npm i koa-router --save 路由控件
const Index = require('./router/index.js');
app.use(Index);// 挂载路由
// router/index.js
const Router = require('koa-router');
const router = new Router();
router.get('/', async (ctx, next) =>{
await next();
ctx.status = 200;
ctx.type= 'json'
ctx.body = {msg:''};
}).routes();
module.exports = router
npm i koa-views --save 加载静态页面
var views = require('koa-views');
// 在所有路由之前使用
app.use( views(path.join( __dirname, 'view' )) );
npm i --save koa-static 加载静态资源
const static = require('koa-static');
app.use(static('./public'));// 加载静态文件
获取ip
console.log( Object.getOwnPropertyNames(ctx.request) );
console.log(ctx.request.ip)