官方文檔 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類型