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()
然后在 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.‘);