Koa 搭建服务
新建一个文件夹 koa_server,进入后
cnpm i -S koa
会生成 node_modules 依赖包,以及 package.json
创建文件 server.js,并写入
const Koa = require(\'koa\');
const app = new Koa();
app.use( async ( ctx ) => {
ctx.body = \'hello koa2\'
})
app.listen(3000)
console.log(\'app running at port 3000.\');
运行 node server.js
即可,这是最简单的http服务。
在ecs安全组,提前开放 3000 端口访问权限。
浏览器中打开 localhost:3000 就能看到 koa 已经在运行。
然后可以加入中间件(middleware)
const Koa = require(\'koa\');
const app = new Koa();
// logger
app.use(async (ctx, next)=>{
await next();
const rt = ctx.response.get(\'X-Response-Time\');
console.log(`${ctx.method} ${ctx.url} - ${rt}`)
})
// x-response-time
app.use(async (ctx, next)=>{
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set(\'X-Response-Time\', `${ms}ms`)
})
app.use( async ( ctx ) => {
ctx.body = \'hello koa2\'
})
app.listen(3000)
console.log(\'app running at port 3000.\');
关于中间件,此处不再展开。
koa 相关内容,可参考 Koa 2
安装 mysql 连接库
cnpm i -S mysql
创建文件 mysql/index.js
var mysql = require(\'mysql\');
var connection = mysql.createConnection({
host : \'MySQL主机地址\',
user : \'root\',
password : \'MySQL登录密码\',
database : \'MySQL数据库\'
});
class Mysql {
query (param) {
return new Promise((resolve, reject) => {
// user 数据表中查询 user_name 为 param 的数据
connection.query(
`SELECT * from user WHERE user_name=\'${param}\'`,
function (error, results, fields) {
if (error) {
return reject(error)
};
resolve(results)
});
})
}
}
module.exports = new Mysql()
这样的配置,可以短期连接,在实际开发中,mysql连接会经常掉线。在这里,引入连接池,改写如下:
var mysql = require(\'mysql\');
var pool = mysql.createPool({
host : \'MySQL主机地址\',
user : \'root\',
password : \'MySQL登录密码\',
database : \'MySQL数据库\'
});
class Mysql {
connect(){
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) {
console.log("连接失败");
reject(err)
} else {
resolve(connection)
}
})
})
}
async query (param) {
let connection = await this.connect()
return new Promise((resolve, reject) => {
// user 数据表中查询 user_name 为 param 的数据
connection.query(`SELECT * from user WHERE user_name=\'${param}\'`,(error, results)=>{
if (error) {
return reject(error)
};
resolve(results)
});
//释放
connection.release();
})
}
}
module.exports = new Mysql()
然后在 server.js 中引用
const Koa = require(\'koa\');
const app = new Koa();
const mysql = require(\'./mysql/index\');
// logger
app.use(async (ctx, next)=>{
await next();
const rt = ctx.response.get(\'X-Response-Time\');
console.log(`${ctx.method} ${ctx.url} - ${rt}`)
})
// x-response-time
app.use(async (ctx, next)=>{
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set(\'X-Response-Time\', `${ms}ms`)
})
app.use(async (ctx) => {
let data = await mysql.query()
ctx.body = {
"code": 10,
"data": data,
"mesg": \'ok\'
}
})
app.listen(3000)
console.log(\'app running at port 3000.\');