1. 程式人生 > >koa2快速搭建api伺服器-建立入口檔案及koa例項

koa2快速搭建api伺服器-建立入口檔案及koa例項

使用koa2快速搭建api伺服器:

app.js  暴露出koa httpserver例項:

const koa =require('koa');
const app =new koa();
const router = require('koa-router')();
const co = require('co');
const convert = require('koa-convert');
const json = require('koa-json');
const onerror =require('koa-onerror');
const bodyparser = require('koa-bodyparser')();
const logger = require('koa-logger');
const server = require('koa-static');
const index = require('./routes/index');
const users = require('./routes/users');

//middleware

app.use(convert(bodyparser));
app.use(convert(json()));
app.use(convert(logger()));
app.use(convert(server(__dirname+'/public')));

app.use(co.wrap(function* (ctx, next) {
  const start = new Date();
  yield next();
  const ms = new Date() - start;
  console.log(`${ ctx.method } ${ ctx.url } - ${ ms }ms`);
}));

router.use('/',index.routes(),index.allowedMethods());
router.use('/users',users.routes(),users.allowedMethods());

app.use(router.routes(),router.allowedMethods());

app.on('error',function(err,ctx){
 log.error('server error',err,ctx);
});

module.exports = app;

index.js 程式入口檔案
const app = require('./app');
app.listen(3000);