angular - 需要帮助解决与全栈应用程序(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.
使这变得困难的是,它似乎大部分时间都可以工作,但偶尔会导致失败。
谢谢您的帮助!
解决方案
推荐阅读
- python - 为什么使用 .set_index() 会给我一个带括号和逗号的索引?
- python - 是否可以使用 pytest 测试 while True 循环(我尝试超时)?
- android - 无法滚动文本视图内容
- selenium - 为什么我们不写 RemoteWebdriver driver = new ChromeDriver();
- javascript - 有没有办法让渐进式 Web 应用程序在不耗尽所有内存的情况下保存大量数据?
- java - 尽管使用了请求包装器,但 Spring 表单输入值在过滤器中读取一次后返回 null
- spring-boot - 在 maven 中使用 jgitver 和本地 repo 时 spring-boot-dependency 版本无效
- c# - 无法继承构造函数,需要对象引用
- windows - 在 Windows 服务中打开的对话框窗口
- javascript - 为什么我们不能在一个库中拥有一个包含 React 和 React-DOM 库的库?