• 通过 ctx 使用 HttpClient

    通过 ctx 使用 HttpClient

    框架在 Context 中同样提供了 ctx.curl(url, options)ctx.httpclient,保持跟 app 下的使用体验一致。这样就可以在有 Context 的地方(如在 controller 中)非常方便地使用 ctx.curl() 方法完成一次 HTTP 请求。

    1. // app/controller/npm.js
    2. class NpmController extends Controller {
    3. async index() {
    4. const ctx = this.ctx;
    5. // 示例:请求一个 npm 模块信息
    6. const result = await ctx.curl('https://registry.npm.taobao.org/egg/latest', {
    7. // 自动解析 JSON response
    8. dataType: 'json',
    9. // 3 秒超时
    10. timeout: 3000,
    11. });
    12. ctx.body = {
    13. status: result.status,
    14. headers: result.headers,
    15. package: result.data,
    16. };
    17. }
    18. }