Koa.js搭建简单服务器,连接数据库
- 1. 环境node v7.6版本以上
- 2. 创建服务安装依赖
- 3. 根目录新建index.js,新建router.js,controller文件夹
- 4. 浏览器访问
- 5. 连接mysql
- 6. 查询测试
- 7、其它
1. 环境node v7.6版本以上
2. 创建服务安装依赖
新建文件夹
mkdir koa && cd koa
初始化
node init -y
安装依赖
node i koa --save
node i @koa/router --save
node i koa-bodyparser --save
node i mysql --save
3. 根目录新建index.js,新建router.js,controller文件夹
index.js
'use strict'
const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser')
const router = require("./router")
app.use(bodyParser())
app.use(router.routes())
app.use((ctx) => {
ctx.body = 'Hello koa'
})
app.listen(10021, () => {
console.log('服务已启动~')
})
router.js
'use strict'
const Router = require("@koa/router")
const router = new Router()
const serverController = require("./controller/server")
router.get("/getFirstFun", serverController.test)
module.exports = router
controller文件夹下新建server.js
'use strict'
class serverController {
static async test(ctx) {
ctx.body = "第一个接口"
}
}
module.exports = serverController
4. 浏览器访问
127.0.0.1:10021/getFirstFun
5. 连接mysql
根目录新建config.js做配置文件
config.js
let config = {
Dbs: {
host: '127.0.0.1',
user: 'root',
password: 'root',
database: 'mydb'
}
}
module.exports = config
根目录新建mysql.js
'use strict'
const mysql = require("mysql")
const {Dbs} = require('./config')
const pool = mysql.createPool({
host: Dbs.host,
user: Dbs.user,
password: Dbs.password,
database: Dbs.database
})
function Query(sql, values) {
return new Promise((resolve, reject) => {
pool.getConnection(function (err, connection) {
if (err) {
reject(err)
resolve({msg: "连接失败", err})
} else {
connection.query(sql, values, (err, rows) => {
if (err) {
reject(err)
resolve({msg: "查询失败", err})
} else {
resolve(rows)
connection.release() //释放连接池
}
})
}
})
})
}
module.exports = {Query}
6. 查询测试
server.js引入mysql
const mysql = require('../mysql')
let sql = `select * from file limit 1`
let result = await mysql.Query(sql)
ctx.body = result
7、其它
其它数据连接参考:https://www.cnblogs.com/joyo-w/p/10660952.html
代码:https://gitee.com/niceguy802/koa.js-server.git