egg restful api学习记录

egg 安装

npm init egg --type=simple
npm i

egg-mysql安装

npm i --save egg-mysql
// 开启插件
// config/plugin.js
 mysql: {
   enable: true,
   package: 'egg-mysql',
 }
 // config/config.default.js
 config.mysql = {
    // 单数据库信息配置
    client: {
      // host
      host: '127.0.0.1',
      // 端口号
      port: '3306',
      // 用户名
      user: 'root',
      // 密码
      password: '123456',
      // 数据库名
      database: 'test',
    },
    // 是否加载到 app 上,默认开启
    app: true,
    // 是否加载到 agent 上,默认关闭
    agent: false,
  };

举例

// router.js
// 查询数据
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);

// controller/user.js
 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;
  }

// service/user.js
  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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值