【问题标题】:Json-server mocking API instead of callsJson-server 模拟 API 而不是调用
【发布时间】:2021-09-05 14:58:56
【问题描述】:

我正在使用 NestJS (NodeJS) 创建一个 API,为了在本地环境中运行它而不运行所有外部 API,我想在我的 API 运行时模拟对外部 API 的调用。

为了做到这一点,我选择了Json-server来做,代码如下:

模拟服务器.ts:

export async function bootstrap() {
  const app = create();
  app.use(
    defaults({
      logger: true,
      static: 'static',
    }),
    router(dbJSON),
    jsonServer.rewriter(routesJSON),
  );

  app.use('/api', router);
}

我也试过了:

export async function bootstrap() {
  const app = create();
  app.use(
    defaults({
      logger: true,
      static: 'static',
    }),
    router(db),
    jsonServer.rewriter(routesJSON),
  );

  app.use('/api', router);
  const port = process.env.mockPort ?? 8080;
  app.listen(port);

main.ts:

async function bootstrap() {
  const app = await NestFactory.create(AppModule)

  const mocks = await import('../mocks/server');
  app.use(await mocks.bootstrap(null));

  await app.listen(DEFAULT_HTTP_PORT, DEFAULT_HOST);
}

但是,我的 API 本身被模拟了,而不是使用 db 和提供给 Json-server 的路由来模拟对外部 API 的调用。

关于如何在运行时模拟对外部 API 的 API 调用有什么想法吗?或者如何让 json-server 模拟调用 httpService 调用而不是 API 本身

【问题讨论】:

    标签: node.js mocking backend nestjs json-server


    【解决方案1】:

    我以前没有尝试过,但我认为你要么需要配置现有的 HttpModule 以有时转发调用,要么用一个新模块包装 HttpModule 来决定是将请求转发到真实服务器还是模拟服务器。

    您可以通过registerHttpModule 提供配置。如果您想注入 ConfigService 以根据确定您是否在本地的环境变量来配置它,请参阅异步配置。配置对象是Axios request config。但是,我看不到通过配置重定向请求的方法。

    HttpModule 使用axios,所以另一个选项是axios interceptors。在请求拦截器中,您可以让它仅在本地运行时覆盖 config.url。要在应用程序的开头设置拦截器,您可以创建一个注入 HttpService 的模块 MyHttpModule,并在 onModuleInit 中获取对 axios 实例的引用并设置拦截器。查看我找到的this example

    【讨论】:

    • 感谢您的帖子,我实际上是使用拦截器使其工作的,以便更准确地供将来参考;我使用 HttpModule 作为拦截器。首先,我检查它是否在正确的模拟环境中运行,如果是,我运行拦截器。拦截器将使用httpService.axiosRef.interceptors.request.use 拦截并将 URL 更改为 mock 的服务器 URL。
    猜你喜欢
    • 2018-08-06
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2020-12-01
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多