zoukankan      html  css  js  c++  java
  • 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类型

  • 相关阅读:
    拥有最多糖果的孩子
    求1+2+…+n
    网络-中间代理
    Header中的Referer属性表示
    ios13.4post请求出现网错错误 network err
    10.8&10.10
    9.23&9.27
    9.16&9.19
    校内模拟赛划水报告(9.9,9.11)
    男人八题 划水题解
  • 原文地址:https://www.cnblogs.com/antyhouse/p/13255494.html
Copyright © 2011-2022 走看看