Angular + Spring. CORS策略
创始人
2024-10-14 13:00:42
0

要解决Angular和Spring之间的CORS策略问题,你可以按照以下步骤进行操作:

  1. 在Spring后端应用程序的配置类中添加CORS配置。在你的Spring Boot应用程序的配置类中,添加@CrossOrigin注解,指定允许跨域请求的来源和方法。
@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:4200") // 允许的来源
                        .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法
                        .allowedHeaders("*") // 允许的头部信息
                        .allowCredentials(true); // 允许携带身份验证信息
            }
        };
    }
}
  1. 在Angular前端应用程序的代码中添加CORS配置。在你的Angular代码中,可以使用Angular的HttpClient模块发送跨域请求。在请求头中添加withCredentials: trueheaders: { 'Content-Type': 'application/json' }
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class MyService {
    constructor(private http: HttpClient) {}

    getData() {
        const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        return this.http.get('http://localhost:8080/api/data', { withCredentials: true, headers });
    }
}
  1. 启动Spring应用程序和Angular应用程序,并确保它们在不同的端口上运行。

通过这些步骤,你可以解决Angular和Spring之间的CORS策略问题,并允许跨域请求。

相关内容

热门资讯

热点讨论!wepoker辅助器... 热点讨论!wepoker辅助器激活码,aapoker怎么拿好牌,攻略教程(有挂辅助)1、很好的工具软...
一分钟了解!佛手大菠萝13道挂... 1、一分钟了解!佛手大菠萝13道挂哪里,wepoker有脚本吗,解密教程(有挂神器)。2、佛手大菠萝...
玩家必看!wepoker透视方... 1、玩家必看!wepoker透视方法,wepoker免费脚本,新2025版(有挂辅助);详细教程。2...
一分钟秒懂!epoker免费透... 一分钟秒懂!epoker免费透视脚本,htx矩阵wepoker辅助,wepoke教程(有挂方法);原...
推荐一款!wepoker怎么下... 您好,wepoker透视脚本免费使用视频这款游戏可以开挂的,确实是有挂的,需要了解加微【136704...
玩家必备科技!WePoKer辅... 玩家必备科技!WePoKer辅助器,wepoker辅助器免费,AI教程(有挂攻略);最新版2024是...
玩家必备科普!wepoker的... 玩家必备科普!wepoker的辅助器,wepoker透视有吗,透牌教程(有挂透明)1、不需要AI权限...
解密关于!wepoker辅助器... 1、解密关于!wepoker辅助器下载,拱趴大菠萝有挂吗,解密教程(有挂透视)。2、拱趴大菠萝有挂吗...
普及知识!智星德州辅助译码插件... 普及知识!智星德州辅助译码插件靠谱吗,wepoker买钻石有用吗,切实教程(有挂透视)准备好在智星德...
我来教教你!竞技联盟透视,po... 我来教教你!竞技联盟透视,poker红龙辅助,2025新版技巧(有挂教程)1、很好的工具软件,可以解...