1 構(gòu)建項(xiàng)目
1.1 安裝koa-generator
在終端輸入:
$ npm install -g koa-generator
1.2 使用koa-generator生成koa2項(xiàng)目
在你的工作目錄下,輸入:
$ koa2 myKoa2
成功創(chuàng)建項(xiàng)目后态蒂,進(jìn)入項(xiàng)目目錄费什,并執(zhí)行npm install命令
$ cd myKoa2
$ npm install
1.3 啟動(dòng)項(xiàng)目
在終端輸入:
$ npm start
項(xiàng)目啟動(dòng)后,默認(rèn)端口號(hào)是3000瘩蚪,在瀏覽器中運(yùn)行可以得到下圖的效果說(shuō)明運(yùn)行成功稿黍。
2 鏈接mysql數(shù)據(jù)庫(kù)
2.1 下載mysql
在項(xiàng)目路徑輸入npm install mysql --save下載mysql
2.2 配置mysql連接池
項(xiàng)目根目錄新建文件夾controllers并創(chuàng)建defaultConfig.js和mysqlConfig.js文件巡球。
//defaultConfig.js
const config = {
// 數(shù)據(jù)庫(kù)配置
database: {
DATABASE: 'xxx', //數(shù)據(jù)庫(kù)名稱(chēng)
USERNAME: 'xxx', //mysql用戶(hù)名
PASSWORD: 'xxx', //mysql密碼
PORT: '3306', //mysql端口號(hào)
HOST: 'xx.xxx.xx.xx' //服務(wù)器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 = `select * from users where name="${name}";`
return allServices.query(_sql)
},
addUserData: (obj) => {
let _sql = "insert into users set name=?,pass=?,avator=?,moment=?;"
return allServices.query(_sql, obj)
},
}
module.exports = allServices;
之后在routes文件夾下users.js
const router = require('koa-router')()
const userService = require('../controllers/mysqlConfig');
router.prefix('/users')
//獲取所有用戶(hù)(GET請(qǐng)求)
router.get('/', async (ctx, next) => {
// console.log(ctx.session.username)
ctx.body = await userService.findAllUser();
})
// 增加用戶(hù)(POST請(qǐng)求)
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
隨后在根目錄下輸入npm start啟動(dòng)項(xiàng)目呢灶,訪(fǎng)問(wèn)localhost:3000/users即可獲取全部用戶(hù)數(shù)據(jù)钉嘹,同樣用ajax的post請(qǐng)求方式操作localhost:3000/users/add即可向數(shù)據(jù)庫(kù)里面添加用戶(hù)數(shù)據(jù)鲸阻。