新手起步可以参考
http://www.jianshu.com/p/6b816c609669
安装完后app.js大概是这样的,其中一些插件是我另外安装的
const Koa = require(‘koa‘) const views = require(‘koa-views‘) const json = require(‘koa-json‘) const onerror = require(‘koa-onerror‘) const bodyparser = require(‘koa-bodyparser‘) const logger = require(‘koa-logger‘) const cors = require(‘koa2-cors‘); const index = require(‘./routes/index‘) const users = require(‘./routes/users‘) const app = new Koa() // error handler onerror(app) //跨域插件 app.use(cors()) // middlewares app.use(bodyparser({ enableTypes:[‘json‘, ‘form‘, ‘text‘] })) app.use(json()) app.use(logger()) //静态文件引用 app.use(require(‘koa-static‘)(__dirname + ‘/public‘)) //模板,pug后缀 app.use(views(__dirname + ‘/views‘, { extension: ‘pug‘ })) // logger app.use(async (ctx, next) => { const start = new Date() await next() const ms = new Date() - start console.log(`${ctx.method} ${ctx.url} - ${ms}ms`) }) // routes // allowedMethods()当前接口运行的methods app.use(index.routes(), index.allowedMethods()) app.use(users.routes(), users.allowedMethods()) // error-handling app.on(‘error‘, (err, ctx) => { console.error(‘server error‘, err, ctx) }); module.exports = app
时间: 2024-10-06 13:35:08