CORS 以某种方式阻止我的 Angular 和 Nestjs 应用程序进行通信

Opt*_*tiq 6 typescript angular nestjs ngxs

我正在使用 Angular 和 NestJS 构建一个应用程序,并使用 NGXS 进行状态管理。我完成了所有设置并为我的应用程序提供服务,并在控制台中收到此错误。

从源“ http://localhost:4200 ”访问“localhost:333/api/product-index”处的 XMLHttpRequest已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome - 扩展名,https。

经过一番研究后,我发现这篇文章解释了如何在我们的 Angular 应用程序中处理 CORS,在检查了它告诉我们要修改的文件后,我发现这些设置已经存在。我对它告诉我们要更新的文件感到困惑server.js,在研究了文件中通常执行的操作后,server.js我得出的结论是,在 Angular 中它一定是该main.ts文件,但我不知道是否需要对文件进行main.ts修改在我的 Nest 应用程序或我的 Angular 应用程序中。nrwl nx我也在我的应用程序中使用monorepo。

这是proxy.conf.json我的角度应用程序中的文件

{
    "/cre8or-maker-backend": {
      "target": "http://localhost:3333",
      "secure": false,
      "logLevel": "debug"
    }
  }
Run Code Online (Sandbox Code Playgroud)

这是我文件中对象serve的对象。architectangular.json

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "cre8or-maker:build",
            "proxyConfig": "apps/cre8or-maker/proxy.conf.json"
          }
Run Code Online (Sandbox Code Playgroud)

正如我之前所说,这些设置已经存在于这些文件中,对我来说唯一新鲜的是关于修改文件的部分server.js,我假设是main.tsAngular 世界中的文件。这是我的main.ts文件的样子

nest main.ts

import { NestFactory } from '@nestjs/core';

import { AppModule } from './app/app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const globalPrefix = 'api';
  app.setGlobalPrefix(globalPrefix);
  const port = process.env.port || 3333;
  await app.listen(port, () => {
    console.log('Listening at http://localhost:' + port + '/' + globalPrefix);
  });
}

bootstrap();
Run Code Online (Sandbox Code Playgroud)

angular main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)

cors已经安装了 npm 包,我只是不知道我还应该做什么才能让它工作,有人可以帮忙吗?

更新 我尝试添加app.enableCors();main.ts我的 NestJs 应用程序中的文件以及修改create(AppModule)函数create(AppModule, {cors: true}),但都没有解决问题。我还添加了以下代码片段,但也没有帮助。

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');
    next();
  });
Run Code Online (Sandbox Code Playgroud)

截至目前,我只定义了一种状态,向后端发出 API 请求。在我的状态中,我有一个看起来像这样的动作

@Action(GetProductIndexList)
    getProductIndexListData({patchState, dispatch, getState}: StateContext<ProductIndexListModel>){

       return this.dataService.fetchProductIndexList().pipe(tap((result)=>{
            const state = getState();

            patchState({items:[...state.items, ...result]});
        }));
    }
Run Code Online (Sandbox Code Playgroud)

dataService我在状态构造函数中调用的服务文件内进行 api 调用。服务文件如下所示。

@Injectable({ providedIn: 'root' })

export class ProductIndexService{

    constructor(private httpClient: HttpClient){}

    private readonly URL: string = 'localhost:3333/api';

    public fetchProductIndexList():Observable<CattegoryIndexItem[]>{
        const path: string = this.URL + '/product-index';

        return this.httpClient.get(path) as Observable<CattegoryIndexItem[]>;
    }
}
Run Code Online (Sandbox Code Playgroud)

在 NestJS 中,我可以成功调用数据而不会出现任何错误,因此我知道控制器已正确设置,但如果有人想了解我如何设置那里的内容,请告诉我,我将用代码更新此问题。

小智 5

对于以下内容,我刚刚在 NX 工作区中开发 Angular 13 和 Nest.js 8 应用程序时遇到了这个问题。

就我而言,我最终通过添加行 app.enableCors(); 解决了这个 CORS 问题。在 Nest.js 应用程序的 main.ts 文件中。

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    const globalPrefix = 'api';
    app.setGlobalPrefix(globalPrefix);
    app.enableCors();
    const port = process.env.PORT || 3000;
    await app.listen(port);
    Logger.log(
        ` Application is running on: http://localhost:${port}/${globalPrefix}`
    );
}

Run Code Online (Sandbox Code Playgroud)

请参阅文档: https: //docs.nestjs.com/security/cors


Opt*_*tiq 2

我从错误中意识到我正在向后端发出请求,localhost:333而不是localhost:3333在服务文件中向后端发送请求。这使得 CORS 错误消失,但我仍然有其他错误,我开始了一个新问题来解决。