04-Egg-处理网络数据

555 阅读1分钟

在EggJS中无论是处理数据库中的数据还是处理网络数据, 都是在Service中处理的

详情: eggjs.org/zh-cn/basic…

废物不多说,直接上代码

const Service = require("egg").Service;

class userService extends Service {
  async find() {
    // 在Service定义的方法中处理数据库和网络的数据即可
    // this.ctx.curl 发起网络调用
    // 发送get不带参数的请求
    // let response = await this.ctx.curl(接口地址);
    // 发送get带参数的请求
    // let response = await this.ctx.curl(接口地址);
    // 发送post不带参数的请求
    // let response = await this.ctx.curl(接口地址);
    // 发送post带参数的请求
    let response = await this.ctx.curl(接口地址, {
      method: "post",
      data: {
        name: "sandy",
        age: 21,
      },
    });
    let data = JSON.parse(response.data);
    console.log("userService", data);
    return data;
  }
}

module.exports = userService;
const Home = require("egg").Controller;

class homeController extends Home {
  async index() {
    this.ctx.body = "egg启动成功";
  }

  async getNews() {
    this.ctx.body = await this.ctx.service.user.find;
  }
}

module.exports = homeController;
module.exports = (app) => {
  const { router, controller } = app;
  router.get("/", controller.home.index);
  router.get("/news", controller.home.getNews);
};