node 搭建服务端项目
技术选型
egg.js
搭建项目
mkdir server-demo && cd server-demo
npm init egg --type=simple
npm i
npm i --save egg-mysql
配置
app/config/config.default.js
修改
config.middleware = ['errorHandler'];
增加
config.errorHandler = {
match: '/api',
};
config.security = {
csrf: {
enable: false,
},
};
config.mysql = {
client: {
// host
host: 'localhost',
// 端口号
port: '3306',
// 用户名
user: 'root',
// 密码
password: 'root',
// 数据库名
database: 'test',
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};
创建数据库
create database if not exists `test` charset utf8mb4;
CREATE TABLE `test`.`tb_user`(
`id` BIGINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`create_time` DATETIME NOT NULL,
PRIMARY KEY (`id`)
);
增加功能
app/controller/user.js
'use strict';
const Controller = require('egg').Controller;
class UserController extends Controller {
async reg() {
const { ctx, service } = this;
// 获取参数
const userInfo = ctx.request.body;
const result = await service.user.reg(userInfo);
ctx.body = {
code: result,
msg: "success"
};
}
async list() {
const {ctx, service} = this;
const query = ctx.request.query;
const result = await service.user.list(query);
ctx.body = {
code: 0,
msg: "success",
data: result
};
}
}
module.exports = UserController;
app/service/user.js
const {Service} = require('egg');
class UserService extends Service {
async reg(userInfo) {
if (userInfo.name == '') {
return -1;
}
let res = await this.app.mysql.query('insert into tb_user (id, name, create_time) values(?, ?, ?)',
[null, userInfo.name, new Date()]);
console.log(res);
let id = res.insertId;
console.log(id);
return 0;
}
async list(query) {
if (query.name == null) {
query.name = '';
}
let list = await this.app.mysql.query('select * from tb_user where name like ?',
['%' + query.name + '%']);
return list;
}
}
module.exports = UserService;
配置路由
app/router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.post('/api/user/reg', controller.user.reg);
router.get('/api/user/list', controller.user.list);
};
app/middleware/error_handler.js
module.exports = () => {
return async function errorHandler(ctx, next) {
try {
await next();
if (ctx.status === 404) {
ctx.body = {
code: -1,
msg: '404 Not Found'
};
}
} catch (err) {
const { app } = ctx;
app.emit('error', err, ctx);
const status = err.status || 500;
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
const error = status === 500 && app.config.env === 'prod' ? 'Internal Server Error' : err.message;
ctx.body = {
code: -1,
msg: error
};
}
}
}
打包部署
本地打包
cd server-demo
npm install --production
tar -zcvf ../release.tgz .
服务器安装node 版本>=12.14.1
npm i egg-scripts --save
上传至服务器目录
mkdir -p /home/app/server-demo
tar -zxvf release.tgz -C /home/app/server-demo/
可以修改package.json
scripts -> start
egg-scripts start --port=7001 --daemon --title=server-demo