koa2是nondejs的开发框架,最近学习nodejs,这里记记笔记
首先安装好nodejs
安装koa2,全局安装
npm install -g koa-generator
创建项目
koa2 test-app
安装依赖并启动
切换到test-app目录下
npm i
npm start
app.js文件修改
创建好项目后,有个默认的结构,有些是我不需要的。有些需要的没有,因此对app.js做下修改。
暂定四个api模块,index.js,users.js,company.js,team.js
有post请求解析插件,
有跨域配置
修改后代码如下
const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const users = require('./routes/users')
const company = require('./routes/company')
const team = require('./routes/team')
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
// 跨域配置
app.use(async (ctx, next)=> {
ctx.set('Access-Control-Allow-Origin', '*')
ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild')
ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
if (ctx.method === 'OPTIONS') {
ctx.body = 200
} else {
await next()
}
})
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(company.routes(), company.allowedMethods())
app.use(team.routes(), team.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
module.exports = app
网友评论