1 Build the project
1.1 Install koa-generator
Type in terminal:
npm install -g koa-generator
1.2 Use koa-generator to generate koa2 project
In your working directory, enter:
koa2 myKoa2
After successfully creating the project, enter the project directory and execute the npm install command
cd myKoa2
npm install
1.3 Start the project
Type in terminal:
npm start
After the project is started, the default port number is 3000. If you run it in the browser, you can get the effect shown in the figure below, indicating that the operation is successful.
2 link mysql database
2.1 Download mysql
Enter npm install mysql --save to download mysql in the project path
2.2 Configure mysql connection pool
Create a new folder controllers in the project root directory and create defaultConfig.js and mysqlConfig.js files.
//defaultConfig.js
const config = {
// 数据库配置
database: {
DATABASE: 'xxx', //数据库名称
USERNAME: 'xxx', //mysql用户名
PASSWORD: 'xxx', //mysql密码
PORT: '3306', //mysql端口号
HOST: 'xx.xxx.xx.xx' //服务器ip
}
}
module.exports = config
//mysqlConfig.js
var mysql = require('mysql');
var config = require('./defaultConfig');
var pool = mysql.createPool({
host: config.database.HOST,
user: config.database.USERNAME,
password: config.database.PASSWORD,
database: config.database.DATABASE
});
let allServices = {
query: function (sql, values) {
return new Promise((resolve, reject) => {
pool.getConnection(function (err, connection) {
if (err) {
reject(err)
} else {
connection.query(sql, values, (err, rows) => {
if (err) {
reject(err)
} else {
resolve(rows)
}
connection.release()
})
}
})
})
},
findUserData: function (name) {
let _sql = "";
if (name) {
_sql = `select * from t_user where realName="${
name}";`
} else {
_sql = `select * from t_user;`
}
return allServices.query(_sql)
},
addUserData: (obj) => {
let _sql = "insert into users set name=?,pass=?,avator=?,moment=?;"
return allServices.query(_sql, obj)
},
}
module.exports = allServices;
Then users.js in the routes folder
const router = require('koa-router')()
const userService = require('../controllers/mysqlConfig');
router.prefix('/users')
//获取所有用户(GET请求)
router.get('/', async (ctx, next) => {
// console.log(ctx.session.username)
ctx.body = await userService.findUserData();
})
// 增加用户(POST请求)
router.post('/add', async (ctx, next) => {
let arr = [];
arr.push(ctx.request.body['name']);
arr.push(ctx.request.body['pass']);
arr.push(ctx.request.body['auth']);
await userService.addUserData(arr)
.then((data) => {
let r = '';
if (data.affectedRows != 0) {
r = 'ok';
}
ctx.body = {
data: r
}
}).catch(() => {
ctx.body = {
data: 'err'
}
})
})
module.exports = router
Then enter npm start in the root directory to start the project, access localhost:3000/users to get all user data, and also use ajax post request to operate localhost:3000/users/add to add user data to the database.