美文网首页
koa 连接数据库

koa 连接数据库

作者: Mokingc | 来源:发表于2019-12-12 00:12 被阅读0次
    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: 'jol' })
    
    let server = new Koa()
    server.listen(8088)
    
    server.context.db = co(conn)
    
    server.use(async (ctx, next) => {
        ctx.set('Access-Control-Allow-Origin', '*')
    
        await next()
    })
    
    let router = new Router()
    
    router.use('/api', require('./routers/api'))
    
    server.use(router.routes())
    

    index.js

    const Router = require('koa-router')
    const Sequelize = require('sequelize');
    
    const sequelize = new Sequelize('jol', 'root', '123456', {
        host: 'localhost',
        dialect: 'mysql' ,
    });
    
    let router = new Router()
    
    router.get('/problem', async ctx => {
        ctx.body = await ctx.db.query('SELECT * FROM problem')
    })
     router.get('/problem/:id', async ctx => {
         let { id } = ctx.params
         ctx.body = await ctx.db.query('SELECT * FROM problem WHERE problem_id=?', [id])
     })
    router.get('/catalog/:parent', async ctx => {
        let { parent } = ctx.params
        ctx.body = await ctx.db.query('SELECT ID, title FROM catalog_table WHERE parentID=?', [parent])
    })
    
    router.get('/problem/:id', async ctx => {
        let { id } = ctx.params
        ctx.body = await ctx.db.query('SELECT * FROM problem WHERE problem_id=?', [id])
    })
    module.exports = router.routes()
    

    相关文章

      网友评论

          本文标题:koa 连接数据库

          本文链接:https://www.haomeiwen.com/subject/bshzgctx.html