【问题标题】:How to fix CORS Error when using the Nest JS framework如何修复 Nest JS 框架中的 CORS 错误
【发布时间】:2021-11-12 12:50:19
【问题描述】:

我在 main.ts 中添加了 cors 包。但它仍然抛出错误。我不明白为什么会抛出这个错误,请您解释一下如何正确处理 cors 问题。

Main.ts

  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.setBaseViewsDir(join(__dirname, '..', 'views'))
  app.setViewEngine('hbs')
  app.use(helmet());
  app.use(express.json({ limit: "50mb" }))
  app.use(express.urlencoded({ limit: "50mb" }))
  
  app.enableCors();

  // app.setGlobalPrefix('api/v1');

  // app.use(csurf({ cookie: false }));

  app.use(cookieParser());

错误

Access to XMLHttpRequest at 'http://localhost:3000' from origin 'http://localhost:4000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我参考了许多文档。所有文档都说在 main.ts 文件中添加 enablecors() 但它会抛出错误

【问题讨论】:

    标签: nestjs nestjs-config nestjs-swagger nestjs-jwt


    【解决方案1】:

    你可以这样做

          const app = await NestFactory.create(AppModule);
          
    
          const options = {
            origin: "*",
            methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
            preflightContinue: false,
            optionsSuccessStatus: 204,
            credentials: true
          };
       
          app.enableCors(options);
    

    【讨论】:

      【解决方案2】:

      你试过了吗

      const app = await NestFactory.create(AppModule, {
        cors: true,
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-07
        • 2020-02-28
        • 2021-11-30
        • 1970-01-01
        • 2021-07-02
        • 1970-01-01
        • 2021-06-25
        • 2021-09-07
        相关资源
        最近更新 更多