服务之路(一)

连接mysql

使用koa框架,连接mysql,查询数据并通过接口返回

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表示函数里有异步操作,await表示紧跟在后面的表达式需要等待结果
  let result = await query();
  result = {
    data: result[0],
    errno: 0,
    errmsg: 'success',
  };
  ctx.body = result;
});

app.listen(3001);

你可能感兴趣的:(服务之路(一))