java - 如何在不使用 Spring Security 的情况下解决 CORS 问题
问题描述
我有这个WebMvcConfigurer
在服务器上部署时工作得很好。但是,当我尝试从本地提供的 Angular 项目向服务器发送请求时,出现以下错误。
从源“http://localhost:4200”访问“https://sub.domain.com/api/staff/logout”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
我的配置如下:
@Configuration
@EnableWebMvc
public class WebMvcConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedOrigins("*")
.allowedHeaders("*")
.exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
.allowCredentials(true).maxAge(3600);
}
/**
* To add our interceptor into Spring configuration, we need to override
* addInterceptors() method WebMvcConfig class that implements WebMvcConfigurer.
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AppInterceptor());
}
};
}
}
我提到了其他问题,我没有找到任何解决我问题的方法。提前致谢。
解决方案
在您的 Angular 应用程序中,您可以添加一个proxy.config.json
将在本地为您解决 CORS 问题的方法。此配置仅影响在本地提供应用程序时,因此在生产环境中不会发生任何变化。
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug",
"changeOrigin": false
}
}
另外,请参阅此答案:https ://stackoverflow.com/a/47537203/9698467和 Angular 文档:https ://angular.io/guide/build#proxying-to-a-backend-server
这个想法是,即使前端和后端都在 上提供服务localhost
,也有一个为 Angular 应用程序提供服务的本地服务器和一个为您的后端提供服务的本地服务器。它们都在不同的端口上提供服务,这会导致跨域问题。通过使用代理,您可以有效地将 Angular 后端请求路由到localhost:8080
,因此从 Angular 客户端的角度来看,一切似乎都在同一个来源。
推荐阅读
- python - 如何在 Pandas DataFrame 中创建一个新列,该列将基于其他列取值?
- hyperledger-fabric - 频道:我的频道收到发现错误:访问被拒绝
- python - 如何使用额外字段扩展架构 SQLAlchemy
- python - Fedora 33 ROS Noetic 'Could not find Boost (missing:python) (found version "1.73.0")' 错误
- r - 从一个创建多个data.frames - 基于选择向量
- video - 使用 gstreamer 压缩视频文件大小
- count - 选择与另一个值不同的计数不起作用
- javascript - 减少java脚本中的对象数组
- mongodb - 具有多个集合的mongo db事务不起作用
- node.js - NestJS JWT 策略认证。有效载荷对所有用户使用相同的安全密钥进行签名