- 通过
ctx使用 HttpClient
通过 ctx 使用 HttpClient
框架在 Context 中同样提供了 ctx.curl(url, options) 和 ctx.httpclient,保持跟 app 下的使用体验一致。这样就可以在有 Context 的地方(如在 controller 中)非常方便地使用 ctx.curl() 方法完成一次 HTTP 请求。
// app/controller/npm.jsclass NpmController extends Controller {async index() {const ctx = this.ctx;// 示例:请求一个 npm 模块信息const result = await ctx.curl('https://registry.npm.taobao.org/egg/latest', {// 自动解析 JSON responsedataType: 'json',// 3 秒超时timeout: 3000,});ctx.body = {status: result.status,headers: result.headers,package: result.data,};}}
