1.安装
npm init
npm i koa koa-static koa-router mysql co-mysql
目录结构:
image.png
2.server.js
const Koa = require('koa')
const Router = require('koa-router')
const mysql = require('mysql')
const co = require('co-mysql')
let conn = mysql.createPool({ host: 'localhost', user: 'root', password: '123456', database: 'oj' })
let server = new Koa()
let router = new Router()
server.listen(8088)
server.context.db = co(conn)
server.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*')
await next()
})
router.use('/api', require('./routers/api'))
server.use(router.routes())
3.index.js
const Router = require('koa-router')
let router = new Router()
router.get('/problem', async ctx => {
ctx.body = await ctx.db.query('SELECT * FROM problem')
})
module.exports = router.routes()
网友评论