https://eggjs.org/zh-cn/core/httpclient.html#mobileAside
将不同业务功能的模块进行拆分成独立的服务
egg的 urllib内置了 httpClient
ctx.curl请求其他API
app.curl(url, opts) 等价于 app.httpClient.request(url, opts)
ctx.curl 默认返回的是 Buffer
ctx.curl options
https://eggjs.org/api/Application.html#curl
class UserService extends Service {async index(url, options) {const { ctx } = this;if (!url) {ctx.throw(400, '缺少请求 URI路径', { code: 400201 });}const {host = '', // 请求地址域名// ...rest,method = 'GET',data = {},dataType = 'json',headers = {},timeout = 10 * 1000,nestedQuerystring = false,} = optionsconst res = await ctx.curl(url, options)if (res.status !== 200 || (res.data?.code !== 0)) {ctx.throw(res.status, res.data.msg, { ...res.data });}return res.data}}
ctx.curl get & post
class CurlController extends Controller {async get() {const { ctx, app } = this;const res = await ctx.curl('http://www.lulongwen.com', {dataType: 'json', // text, 默认 dataType是 buffertimeout: 3000, // 3 秒超时})}async post() {const { ctx, app } = this;const res = await ctx.curl('http://www.lulongwen.com/login', {method: 'POST',contentType: 'json',data: ctx.request.body,dataType: 'json',})}}
router.js里面设置路由
router.get('cur/get', controller.curl.get)router.post('cur/post', controller.curl.post)
dataType 返回值类型
ctx.curl默认返回的是 Buffer,需要设置 dataType来解析成不同的类型
dataType进行 data解析
app.curl
src/app.js
module.exports = app => {app.beforeStart(async () => {// 示例:启动的时候去读取 https://registry.npm.taobao.org/egg/latest 的版本信息const result = await app.curl('https://registry.npm.taobao.org/egg/latest', {dataType: 'json',});app.logger.info('Egg latest version: %s', result.data.version);});};
