【问题标题】:How to handle CORS in NestJs Fastify如何在 NestJs Fastify 中处理 CORS
【发布时间】:2020-05-22 02:38:25
【问题描述】:

我正在尝试在 Angular 应用程序中处理 CORS。在我的main.ts:

const adapter = new FastifyAdapter();
const app = await NestFactory.create<NestFastifyApplication>(AppModule, adapter);
app.enableCors();

但我的 Angular 客户端会产生 CORS 错误。

这是 NestJS 中的错误吗?

【问题讨论】:

  • 请从您的 Angular 应用控制台添加一些错误输出。

标签: angular nestjs


【解决方案1】:

您需要安装 fastify-cors 软件包:

npm i fastify-cors

然后,在您的代码中:

fastify.register(require('fastify-cors'));

【讨论】:

    【解决方案2】:
    app.register(require('fastify-cors'), {
        origin: true,
        allowedHeaders: [
            'Origin', 
            'X-Requested-With', 
            'Accept', 
            'Content-Type', 
            'Authorization'
        ],
        methods: ['GET', 'PUT', 'OPTIONS', 'POST', 'DELETE'],
      });
    
    You need to add this library [`fastify-cors`][1]. 
    
    Please remove `app.enableCors()` before using above code.
    
    
      [1]: https://github.com/fastify/fastify-cors
    

    【讨论】:

      【解决方案3】:
      const CORS_OPTIONS = {
          origin: ['http://127.0.0.1:5500'], // or '*' or whatever is required
          allowedHeaders: [
          'Access-Control-Allow-Origin',
          'Origin',
          'X-Requested-With',
          'Accept',
          'Content-Type',
          'Authorization',
        ],
        exposedHeaders: 'Authorization',
        credentials: true,
        methods: ['GET', 'PUT', 'OPTIONS', 'POST', 'DELETE'],
      };
      
      const adapter = new FastifyAdapter();
      adapter.enableCors(CORS_OPTIONS) //<------------ this line 
      const app = await NestFactory.create<NestFastifyApplication>(AppModule, 
      adapter);
      //app.enableCors(); <-- remove this line and you should see cors enabled ; also fastify documentation has all the options documentation
      

      【讨论】:

        猜你喜欢
        • 2020-05-18
        • 2020-06-19
        • 2021-12-26
        • 2022-08-17
        • 2020-05-09
        • 2023-03-16
        • 1970-01-01
        • 2019-09-16
        • 2021-02-12
        相关资源
        最近更新 更多