首页 > 解决方案 > 需要帮助解决与全栈应用程序(Angular 和 NestJS)不一致的 CORS 策略问题

问题描述

我想弄清楚为什么会发生这个问题,我束手无策。有时,通常在第一次请求资源时,服务器不会附加Access-Control-Allow-Origin标头,但如果您刷新并尝试再次请求它通常会起作用。我会说这个错误发生在 1/10 个请求(至少感觉是这样)。

幸运的是,NestJS 内置了 CORS 功能,所以我所做的唯一配置是:

const app = await NestFactory.create<NestExpressApplication>(AppModule);

app.enableCors({
    origin: [/http:\/\/localhost/, /https?:\/\/([a-z0-9]+[.])*example.com/],
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With'],
    credentials: true,
    preflightContinue: true,
    optionsSuccessStatus: 200
});

...

我还观察到,简单地使用像下面这样的不太安全的配置仍然会偶尔导致相同的请求失败。这对我来说没有意义,因为任何来源都应该是“有效的”,但它仍然失败。

app.enableCors({
    origin: true,
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']
});

在 Angular 方面,我刚刚得到了一个请求拦截器,它将withCredentials字段设置为 true。

从客户端看到的错误:

Access to fetch at 'https://api.example.com/api/blog/posts' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

但有时,它也来自XMLHttpRequest对象......

Access to XMLHttpRequest at 'https://api.example.com/api/home' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

使这变得困难的是,它似乎大部分时间都可以工作,但偶尔会导致失败。

谢谢您的帮助!

标签: angularcorsnestjs

解决方案


推荐阅读