egg 安装
npm init egg --type=simple
npm i
egg-mysql安装
npm i --save egg-mysql
mysql: {
enable: true,
package: 'egg-mysql',
}
config.mysql = {
client: {
host: '127.0.0.1',
port: '3306',
user: 'root',
password: '123456',
database: 'test',
},
app: true,
agent: false,
};
举例
router.get('/findall', controller.user.findall);
router.post('/add', controller.user.add);
router.delete('/delete/:id', controller.user.delete);
router.put('/update', controller.user.update);
async findall() {
const data = await this.service.user.findall();
this.ctx.body = data;
}
async add() {
const params = this.ctx.request.body;
const data = await this.service.user.add(params);
this.ctx.body = data;
}
async delete() {
const id = this.ctx.params.id;
const data = await this.service.user.delete(id);
this.ctx.body = data;
}
async update() {
const params = this.ctx.request.body;
const data = await this.service.user.update(params);
this.ctx.body = data;
}
async findall() {
const user = await this.app.mysql.select('user');
return { user };
}
async add(params) {
const result = await this.app.mysql.insert('user', { id: params.id, name: params.name, password: params.password });
return { result };
}
async delete(id) {
const result = await this.app.mysql.delete('user', { id });
return { result };
}
async update(params) {
const option = {
where: {
id: params.id,
},
};
const row = {
name: params.name,
};
const result = await this.app.mysql.update('user', row, option);
return { result };
}
总结
1.什么是restful API ?
答:restful API 就是一种命名规范。
2.HTTP 状态码就是一个三位数,分成五个类别。
答:# 1xx:相关信息
# 2xx:操作成功
# 3xx:重定向
# 4xx:客户端错误
# 5xx:服务器错误
https://zhanglin.blog.csdn.net/article/details/102927209