欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

node+koa链接mysql

程序员文章站 2022-06-27 22:58:42
const Koa = require('koa');const KoaStaticCache = require('koa-static-cache');const KoaRouter = require('koa-router');const mysql = require('mysql2');const koacors = require('koa-cors')const KoaBody = require('koa-body');// 链接数据库const connection =...
const Koa = require('koa');
const KoaStaticCache = require('koa-static-cache');
const KoaRouter = require('koa-router');
const mysql = require('mysql2');
const koacors = require('koa-cors')
const KoaBody = require('koa-body');


// 链接数据库
const connection = mysql.createConnection({
    host: 'sqlIp',
    user: 'kkbBase',
    password: 'hyt0617',
    database: 'kkb'
}, () => {
    console.log('mysql连接成功');
});


const app = new Koa();

/**
* 静态资源代理
*  KoaStaticCache 中间件 
*/
app.use(KoaStaticCache({
    prefix: '/public',
    dir: './public',
    dynamic: true,
    gzip: true
}));


/**
 * 动态访问
 */
const router = new KoaRouter();

router.get('/register', async ctx => {
    let users = await query(
        "SELECT * FROM `users`"
    );
    ctx.body = users;
})

app.use(koacors());//允许跨域
app.use(router.routes());
app.listen(8888, () => {
    console.log('服务器启动成功 http://localhost:8888');
});
function query(sql, prepared) {
    return new Promise((resolve, reject) => {
        connection.query(
            sql,
            prepared,
            function (err, results, fields) {
                if (err) {
                    reject(err);
                } else {
                    resolve(results);
                }
            }
        );
    })
}

本文地址:https://blog.csdn.net/qq_43604182/article/details/111983354

相关标签: mysql node nodejs