0

我在 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()但它抛出错误

4

2 回答 2

0

你试过这个

const app = await NestFactory.create(AppModule, {
  cors: true,
});
于 2021-09-18T03:16:10.257 回答
0

你可以做这样的事情

      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);
于 2021-09-19T14:38:51.787 回答