数据库
首页 > 数据库> > koa连接mysql数据库

koa连接mysql数据库

作者:互联网

app.js中的代码:
const Koa = require('koa2');
const app= new Koa();
const port = 5050;

const Router = require('koa-router');
const router = new Router();

const poolSql =require('./db.js');
const cors = require('koa2-cors');
const bodyparser = require('koa-bodyparser');

router.get('/', async (ctx)=>{
    ctx.body ='这是首页';
})

router.get('/query',async(ctx)=>{
    ctx.status=200;
    try{
        let _sql = "select * from info";
        let _data = await poolSql(_sql);
        ctx.body={
            errMessage:"OK",
            result:true,
            data:_data
        }


    }catch(err){
        ctx.body={
            errMessage:"查询失败",
            result:false,
            data:null
        }
    }

})

app.use(cors()).use(bodyparser()).use(router.routes(),router.allowedMethods());


app.listen(port,()=>{
    console.log(`server start at http://127.0.0.1:${port}`);
})

db.js中的代码:

const mysql = require('mysql');

const poolSql = mysql.createPool({
    host:"localhost",
    port:"3306",
    user:"root",
    password:'root',
    database:"clover"
})

function query(sql,value){
    return new Promise((resolve,reject)=>{
        poolSql.query(sql,value,(err,result)=>{
            if(err){
                reject(err)
            }else{
                resolve(result)
            }
        })
    })
}

module.exports=query;

 

标签:const,koa,数据库,ctx,result,mysql,router,app,require
来源: https://www.cnblogs.com/wen-kang/p/16630816.html