springboot 支持跨域

 

1.请求如下

 

公司前端页面请求地址为:      https://www.api.xx.com/

java后端项目地址为:              https://www.api.xx.com/

当前端页面请求到java后端项目的时候,发生跨域问题

 

报错信息如下

 

2.原因如下,

需要

 

跨域资源共用(Cross-Origin Resource Sharing (CORS),是一种使用额外HTTP标头令目前浏览网站的使用者代理取得存取其他来源(网域)伺服器特定资源权限的机制。当使用者代理请求一个不是目前文件来源——例如来自于不同网域(domain)、通讯协定(protocol)或通讯埠(port)的资源时,会建立一个跨来源HTTP请求(cross-origin HTTP request )是一种使用额外HTTP标头令目前浏览网站的使用者代理取得存取其他来源(网域)伺服器特定资源权限的机制。当使用者代理请求一个不是目前文件来源——例如来自于不同网域(domain)、通讯协定(protocol)或通讯埠(port)的资源时,会建立一个跨来源HTTP请求(cross-origin HTTP request )

基于安全性考量,程式码所发出的跨来源HTTP请求会受到限制。例如,XMLHttpRequestFetch都遵守同源政策(same-origin policy)。这代表网路应用程式所使用的API除非使用CORS标头,否则只能请求与应用程式相同网域的HTTP资源。

3.代码解决

可以简单理解为这是一种安全机制!而我们需要访问跨域的,。可以适用下列代码。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Spring 解决跨域问题
 * 
 * @Author luch
 *
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {



	@Bean
	public CorsFilter corsFilter() {
		final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
		final CorsConfiguration corsConfiguration = new CorsConfiguration();
		/* 是否允许请求带有验证信息 */
		corsConfiguration.setAllowCredentials(true);
		/* 允许访问的客户端域名 */
		corsConfiguration.addAllowedOrigin("*");
		/* 允许服务端访问的客户端请求头 */
		corsConfiguration.addAllowedHeader("*");
		/* 允许访问的方法名,GET POST等 */
		corsConfiguration.addAllowedMethod("*");
		urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
		return new CorsFilter(urlBasedCorsConfigurationSource);
	}



}

这里用了@configure注解,记得需要进行扫描

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值