node使用egg.js用ctx.curl从后端拿数据的接口的封装

官方文档 https://eggjs.org/api/ 搜 curl

const Service = require('egg').Service

class tarsServerService extends Service {

  /**
   * 调用tars服务API(HTTP)
   * @param { String } url API路径
   * @param { Object } options curl的配置信息
   * @return { Object } 返回请求结果数据
   */
  async tarsServerHttp(url = '', options = {}) {
    const { ctx } = this
    if (!url) {
      ctx.throw(400, '缺少请求Api路径', { code: 400201 })
    }
    const {
      host = '', // 配置请求地址域名
      method = 'GET',
      data = {},
      dataType = 'json',
      headers = {},
      timeout = 10 * 1000,
      nestedQuerystring = false,
      // 此处只列了常见属性,有需要新增参数的,在此处添加
      // 更多配置,查看 https://www.npmjs.com/package/urllib
    } = options
    const res = await ctx.curl(
      `${host ? host : this.config.tarsServerHost}${url}`,
      {
        method,
        data,
        dataType,
        headers,
        timeout,
        nestedQuerystring,
      }
    )
    if (res.status !== 200 || (res.data.code && res.data.code !== 0)) {
      ctx.throw(res.status, res.data.msg, { ...res.data })
    }
    return res.data
  }
}
module.exports = tarsServerService

egg上面默认的dataType是buffer,这里改成json后,以后使用导出文件,要记得加上buffer类型

原文地址:https://www.cnblogs.com/antyhouse/p/13255494.html