node+koa链接mysql
程序员文章站
2022-03-19 15:25:38
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