- 全局安装Koa命令行工具:
npm install -g @koa/cli
2. 创建新项目:
koa new my-app
这将生成如下目录结构:
my-app ├── app.js ├── package.json └── src └── index.js
3. 安装依赖:
cd my-app npm install
4. 启动项目:
npm start
5.安装mysql2
yarn add mysql2
6.创建配置mysql连接池文件
const mysql = require('mysql2/promise');
//创建连接池
const pool = mysql.createPool({
host: '',
user: '',
password: ',
database: '
})
//查询方法
const query = async (sql,values) => {
let connection;
try {
connection = await pool.getConnection();
const [results,fields] = await connection.execute(sql,values);
return {
status : 200,
results
};
} catch (err) {
throw err;
} finally {
connection.release();
}
}
module.exports = { query }
7.在routes下面的文件使用:
const { query } = require('../config/mysql');
var router = require('koa-router')();
router.get('/swiper' , async ctx => {
const res = await query(`SELECT * FROM swiper`);
ctx.body = res.results
})
module.exports = router;
8.在postman中请求
9.返回结果