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);




你可能感兴趣的:(node.js)