当使用nginx部署时,NestJs在所有路由上返回404,但在本地一切正常

时间:2020-09-19 12:50:06

标签: node.js docker nginx jenkins nestjs

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { CoreConfig } from './config.const';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { NestApplicationOptions } from '@nestjs/common';

async function bootstrap() {
  const httpOptions ={
    requestCert: false,
    rejectUnauthorized: true,
  };
  const app = await NestFactory.create(AppModule);
  const options = new DocumentBuilder()
    .addServer(`http://localhost:${CoreConfig.app.port}`)
    .setTitle('test UI/AI')
    .setDescription('UI meta service')
    .setVersion('1.0')
    .addTag('test')
    .addBearerAuth({type:'http', bearerFormat: 'authorization'})
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('docs', app, document);
  app.enableCors();
  app.setGlobalPrefix('ui');
  await app.listen(CoreConfig.app.port);
}

bootstrap().then();

使用nginx部署我的应用程序时,我们有一个前缀,用于路由到此NestJs应用程序(UI),所有请求均以404结尾,但是在本地一切正常。

这是实例部署的结果

{"statusCode":404,"error":"Not Found","message":"Cannot GET /ui/"}

本地http://prntscr.com/uk2dgj

1 个答案:

答案 0 :(得分:0)

我将 ingress-nginx 配置为将所有访问 def suppress(D, threshold): return {i:0 if x < threshold else i:x for (i, x) in D.items()} 的流量发送到我的后端(NestJS 应用)。

问题是 /api/ 部分被发送到我的 NestJS 应用程序,而这些路由都不存在。例如,我的 graphql 端点位于 /api/,但使用 ingress-nginx,所有流量都将发送到 /graphl,因此 404'ing。

我的解决方法是添加“api”的 global prefix within NestJS 并手动将 graphql 路径设置为 /api/graphql

您也可以使用 ingress-nginx 重写从通过 ingress-nginx rewrite targets 发送到后端的路由中删除 /api/graphql