NestJS 在生产模式下启用 CORS

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

我有一个非常常见的问题无法解决...

一般来说,我的 Angular + NestJS 项目处于生产模式。基础设施或请求响应流程如下所示:

mywebsite.io (client browser) ---> proxy.mywebsite.io

在代理服务器上的

main.ts
文件中,我有以下配置:

const whitelist = [
  'http://localhost:4200',
  'https://mywebsite.io',
  'https://proxy.mywebsite.io'
];

const app = await NestFactory.create(AppModule);
const port = process.env.PROXY_PORT;

app.setGlobalPrefix('/api');
app.use(json({ limit: '50mb' }));
app.use(urlencoded({ extended: true, limit: '50mb' }));

app.enableCors({
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'],
  credentials: true,
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      console.log('allowed cors for (API Proxy):', origin);
      callback(null, true);
    } else {
      console.log('blocked cors for:', origin);
      callback(new Error('Not allowed by CORS (API Proxy)'));
    }
  }
});

问题是,在开发模式下,在

localhost
上它工作得很好,而在生产中我在控制台中收到此错误消息:

Access to XMLHttpRequest at 'https://proxy.mywebsite.io/api/proxy/products/latest-products' from origin 'https://mywebsite.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

此外,当我打开生产日志时,我什至看不到来自

console.log
函数的消息。老实说,我不知道为什么会发生这种情况。我读过几篇有关它的文章并尝试复制其中的逻辑,但没有成功。您对为什么会发生这种情况以及如何解决这个问题有什么想法吗?

提前谢谢大家!

cors nestjs
1个回答
0
投票

最近nestjs也出现了类似CORS问题,显然你的cors配置是正确的。 当您的 API 配置为使用 HTTP 协议并且正在接收来自具有 HTTPS 协议的 URL 的请求时,可能会发生此错误,如果您的 API 使用 HTTP 协议,请为您的域激活 SSL 证书,这就是我解决问题的方法使用 CORS,为 API 和我的前端(Web)激活 SSL。

我的 API 中的 CORS 配置如下例所示:

app.enableCors({
    exposedHeaders: ['X-Total-Count', 'X-Current-Page', 'X-Item-Count', 'X-Items-Per-Page', 'X-Total-Items', 'X-Total-Pages'],
    origin: function (origin, callback) {
        const whitelist = ['https://url-frontend-one.com', 'https://url-frontend-two.com', 'https://url-frontend-three.com'];

        if (whitelist.indexOf(origin) !== -1) {
          callback(null, true);
        } else {
          callback(
            new HttpException('Not allowed by CORS', HttpStatus.UNAUTHORIZED),
          );
        }
    },
})
© www.soinside.com 2019 - 2024. All rights reserved.