連接mysql
使用koa框架爆班,連接mysql魄懂,查詢數(shù)據(jù)并通過接口返回
const koa = require('koa');
const app = new koa();
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'xxx',
database: 'xxx'
});
connection.connect();
app.use(async(ctx, next) => {
let query = () => {
//注意此處需要使用Promise對象包裹
return new Promise((resolve, reject) => {
connection.query('select * from user', (error, results, fields) => {
if (error) throw error;
console.log(results);
resolve(results);
});
});
}
// async await: async表示函數(shù)里有異步操作,await表示緊跟在后面的表達式需要等待結(jié)果
let result = await query();
result = {
data: result[0],
errno: 0,
errmsg: 'success',
};
ctx.body = result;
});
app.listen(3001);