const Koa = require('koa') const path = require('path') const koaStatic = require('koa-static') const bodyParser = require('koa-bodyparser') const session = require('koa-session-minimal') const MysqlStore = require('koa-mysql-session') const cors = require('koa2-cors') const config = require('./config') const routers = require('./routers/index') const app = new Koa() //跨域处理 app.use(cors({ origin: function (ctx) { if (ctx.url === '/cors') { return "*"; // 允许来自所有域名请求 } return 'http://localhost:8000'; }, exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'], maxAge: 5, credentials: true, allowMethods: ['GET', 'POST', 'DELETE'],//设置允许的HTTP请求类型 allowHeaders: ['Content-Type', 'Authorization', 'Accept'], })) // session存储配置 const sessionMysqlConfig= { user: config.database.USERNAME, password: config.database.PASSWORD, database: config.database.DATABASE, host: config.database.HOST, } // 配置session中间件 app.use(session({ key: 'USER_SID', store: new MysqlStore(sessionMysqlConfig) })) // 配置ctx.body解析中间件 app.use(bodyParser()) // 配置静态资源加载中间件 app.use(koaStatic( path.join(__dirname , './static') )) // 初始化路由中间件 app.use(routers.routes()).use(routers.allowedMethods()) // 监听启动端口 app.listen( config.port ) console.log(`the server is start at port ${config.port}`)