Angular Service Worker阻止调用API

问题描述 投票:0回答:1

我有一个Angular应用程序,它使用NestJS应用程序的API端点。

为了将整个应用程序部署到Heroku,我构建了Angular应用程序,并将/ dist文件夹的内容放在我的NestJS应用程序中。

我使用的是Google身份验证系统。基本上,Angular调用一个API端点,将用户重定向到Google的登录界面,一旦完成,它就会回调我的API,重定向回前面的URL,如图所示:auth process

我的问题是:当我在Angular应用程序中运行服务工作者时,每次单击“使用Google登录”链接时,都会收到以下错误消息:

错误错误:未捕获(承诺):错误:无法匹配任何路由。网址细分:'api / auth / google'错误:无法匹配任何路由。网址细分:'api / auth / google'

在此之后,当我尝试通过我的浏览器直接调用API端点(如https://myapp.herokuapp.com/api/albums)时,我收到相同的错误消息。但不是以Postman为例。

所以我决定从Angular部分删除服务工作者,现在一切正常。因此,服务工作者阻止我调用API端点。

如何正确配置以避免这种问题?

如果您需要更多信息,请参阅以下内容:

这是我的main.ts

async function bootstrap() {
  const configService = new ConfigService(CONFIG_SERVICE_PATH);
  const app = await NestFactory.create(AppModule);
  const httpRef = app.get(HTTP_SERVER_REF);

  app.enableCors();

  console.log('***** NODE ENV IS: ' + process.env.NODE_ENV); // <-- returns 'production' 
  console.log('***** IS PRODUCTION ? ' + configService.get('PRODUCTION')); // <-- returns 'true'

  if (configService.get('PRODUCTION') === 'true') {
    app.useStaticAssets(join(__dirname, '../front')); // <-- Angular folder
    app.useGlobalFilters(new AllExceptionsFilter(httpRef));
  } else {
    app.useStaticAssets(join(__dirname, '..', 'public'));
  }

  await app.listen(process.env.PORT || configService.get('PORT'));
}

我的AllExceptionsFilter

@Catch(NotFoundException)
export class AllExceptionsFilter extends BaseExceptionFilter {
  constructor(@Inject(HTTP_SERVER_REF) applicationRef: HttpServer) {
    super(applicationRef);
  }

  /**
   * This filter will serve the correct response for a request to the API or a request to the front part.
   */
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const req = ctx.getRequest();

    if (req.path && req.path.startsWith('/api')) {
      super.catch(exception, host);
    } else {
      response.sendFile(resolve(__dirname, '../../front/index.html'));
    }
  }
}

我的LoginComponent(Angular):

<a href="{{ loginUrl }}" class="google-button">
  <span class="google-button__text">Sign in with Google</span>

get loginUrl(): string {
  const url = environment.backendUrl + '/auth/google';
  console.log('Login url: ' + url); // <-- logs 'https://myapp.heroku.com/api/auth/google'
  return url;
}
angular heroku service-worker progressive-web-apps nestjs
1个回答
0
投票

@Flobesst,贴出来作为答案:)

看看这篇文章:Angular 5 and Service Worker: How to exclude a particular path from ngsw-config.json

© www.soinside.com 2019 - 2024. All rights reserved.