教程 > nest.js 中文教程 > 阅读:1275

nest.js http 模块——迹忆客-ag捕鱼王app官网

axios 是一个功能丰富的 http 客户端包,被广泛使用。 nest 封装了 axios 并通过内置的 httpmodule 将其公开。 httpmodule 导出 httpservice 类,该类公开基于 axios 的方法来执行 http 请求。 该库还将生成的 http 响应转换为 observables。

我们还可以直接使用任何通用的 node.js http 客户端库,包括 got 或 undici。

安装

要开始使用它,我们首先安装所需的依赖项。

$ npm i --save @nestjs/axios

开始使用

安装过程完成后,要使用 httpservice,首先导入 httpmodule

@module({
  imports: [httpmodule],
  providers: [catsservice],
})
export class catsmodule {}

接下来,使用普通的构造函数注入来注入 httpservice

httpmodule 和 httpservice 是从 @nestjs/axios 包中导入的。

@injectable()
export class catsservice {
  constructor(private httpservice: httpservice) {}
  findall(): observable> {
    return this.httpservice.get('http://localhost:3000/cats');
  }
}

axiosresponse 是从 axios 包中导出的接口($ npm i axios)。

所有 httpservice 方法都返回一个包装在 observable 对象中的 axiosresponse


配置

axios 可以配置多种选项来自定义 httpservice 的行为。 要配置底层 axios 实例,请在导入时将可选选项对象传递给 httpmodule 的 register() 方法。 这个选项对象将直接传递给底层的 axios 构造函数。

@module({
  imports: [
    httpmodule.register({
      timeout: 5000,
      maxredirects: 5,
    }),
  ],
  providers: [catsservice],
})
export class catsmodule {}

异步配置

当我们需要异步而不是静态地传递模块选项时,请使用 registerasync() 方法。 与大多数动态模块一样,nest 提供了几种处理异步配置的技术。

一种技术是使用工厂函数:

httpmodule.registerasync({
  usefactory: () => ({
    timeout: 5000,
    maxredirects: 5,
  }),
});

和其他工厂提供者一样,我们的工厂函数可以是异步的,可以通过 inject 注入依赖。

httpmodule.registerasync({
  imports: [configmodule],
  usefactory: async (configservice: configservice) => ({
    timeout: configservice.get('http_timeout'),
    maxredirects: configservice.get('http_max_redirects'),
  }),
  inject: [configservice],
});

或者,我们可以使用类而不是工厂来配置 httpmodule,如下所示。

httpmodule.registerasync({
  useclass: httpconfigservice,
});

上面的构造在 httpmodule 中实例化了 httpconfigservice,使用它来创建一个选项对象。 请注意,在此示例中,httpconfigservice 必须实现 httpmoduleoptionsfactory 接口,如下所示。 httpmodule 将调用所提供类的实例化对象上的 createhttpoptions() 方法。

@injectable()
class httpconfigservice implements httpmoduleoptionsfactory {
  createhttpoptions(): httpmoduleoptions {
    return {
      timeout: 5000,
      maxredirects: 5,
    };
  }
}

如果要重用现有选项提供程序而不是在 httpmodule 中创建私有副本,请使用 useexisting 语法。

httpmodule.registerasync({
  imports: [configmodule],
  useexisting: httpconfigservice,
});

查看笔记

扫码一下
查看教程更方便
网站地图