springbootCORS跨域请求解决三⼤⽅案,springbootCorsFilter。。。
springboot CORS 跨域请求解决三⼤⽅案,springboot CorsFilter解决跨域问题
springboot CORS解决 No 'Access-Control-Allow-Origin' header is present on the requested resource
================================
©Copyright 蕃薯耀 2020-11-24
跨域请求,⼀般是在页⾯调⽤ajax请求向别的应⽤服务发送请求,因域名不相同,导致跨域
解决跨域请求的⽅式有:
⼀、远程服务器⽀持跨域请求(CORS 跨域)
⼆、使⽤nginx反向代理
三、服务器端使⽤Http请求
四、使⽤jsonp(需要应⽤服务器⽀持)
下⾯以远程服务器⽀持跨域请求(CORS 跨域)为例:
其中有三种⽅式让远程服务器⽀持跨域请求
⽅式⼀、使⽤注解:@CrossOrigin
1、在类上加注解,表⽰类下所有⽅法都⽀持跨域请求
@CrossOrigin
@RestController
@RequestMapping("cross")
public class AaaController {
}
2、在⽅法加注解,表⽰该⽅法运动跨域请求
@RestController
@RequestMapping("cross")
public class AaaController {
@CrossOrigin
@RequestMapping("/bbb")
public Result bbb(HttpServletRequest request, HttpServletResponse response) throws Exception {
……
}
}
⽅式⼆、实现WebMvcConfigurer接⼝,重写addCorsMappings⽅法(官⽅⽂档全局配置跨域请求使⽤的是此⽅式)
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.http.MediaType;
import org.verter.HttpMessageConverter;
import org.verter.json.MappingJackson2HttpMessageConverter;
import org.springframework.fig.annotation.CorsRegistry;
import org.springframework.fig.annotation.WebMvcConfigurer;
st.util.JsonUtil;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/
**
* 解决跨域请求
* @return
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("*")
.
maxAge(3600);
WebMvcConfigurer.super.addCorsMappings(registry);
}
/**
* 解决@RestController返回json结果时,IE浏览器出现下载json⽂件的现象。
* @return
*/
@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
List<MediaType> supportedMediaTypes  = new ArrayList<MediaType>();
supportedMediaTypes.add(new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8")));
supportedMediaTypes.add(new MediaType(MediaType.TEXT_HTML, Charset.forName("UTF-8")));
jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
jsonConverter.Mapper());//设置使⽤jackson转换器
return jsonConverter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jackson2HttpMessageConverter());
}
}
⽅式三、使⽤CorsFilter过滤器
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.s.CorsConfiguration;
import org.s.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class HttpFilterConfig {
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
CorsConfiguration corsConfig = new CorsConfiguration();
corsConfig.setAllowCredentials(true);
corsConfig.addAllowedOrigin(CorsConfiguration.ALL);
corsConfig.addAllowedMethod(CorsConfiguration.ALL);
corsConfig.addAllowedHeader(CorsConfiguration.ALL);
//默认可不设置这个暴露的头。这个为了安全问题,不能使⽤*。设置成*,后⾯会报错:throw new IllegalArgumentException("'*' is not a valid exposed header value");
//corsConfig.addExposedHeader("");
corsConfig.setMaxAge(3600L);
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
FilterRegistrationBean<CorsFilter> corsBean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(configSource));
corsBean.setName("crossOriginFilter");
corsBean.setOrder(0);//这个顺序也有可能会有影响,尽量设置在前⾯
return corsBean;
}
}
前端页⾯调⽤⽰例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>跨域请求</title>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
</head>
<body>
<div>跨域请求</div>
<script type="text/javascript">
function ajax(){
console.log("ajax()");
$.ajax({
//async: false,//设置为同步,默认为异步(⼀般不需要)
url : "aaa:7010/gtkjCghj/workflow/processes",  //aaa域名修改host⽂件
type : "post",
dataType : "json",
//contentType: "application/json;charset=UTF-8",//contentType如果设置成application/json;charset=UTF-8,就会会变成复杂请求,导致发送2次请求,第⼀次是options请求,第⼆次才是真正的请求。        data : {
"processName" : "报批",
"gxDocNo": "f2-202000234",
"ssotoken":"eyJpc3N1Y2Nlc3MiOiJ0cnVlIiwiZmFpbHJlc29uIjoiIiwiYWNjb3VudCI6Inplbmd6aW0iLCJ0b2tlbiI6ImE5YzA5YTdjYWRlOTQwNjFiNzdmYzMxNjhkZDI2Mzc3In0=.Eg4DFhERDQ=="
},
complete : function(XMLHttpRequest, textStatus){
//alert("textStatus="+textStatus);
},
error : function(XMLHttpRequest, textStatus, errorThrown){
if("error" == textStatus){
alert("服务器未响应,请稍候再试");
}else{
alert("请求失败,textStatus="+textStatus);
}
},
success : function(data){
if(data != null){
console.log("data===" + JSON.stringify(data));
}else{
alert("返回结果为空!");
}
}
});
};
ajax();
</script>
</body>
</html>
注意事项:
需要注意的是ajax请求中的contentType:
contentType默认的值是:application/x-www-form-urlencoded,当不设置或者为默认值时,这个是简单请求,只发送1次真正的请求。
如果contentType设置成"application/json;charset=UTF-8"会变成复杂请求,导致发送2次请求,第⼀次是options请求,第⼆次才是真正的请求。
部分服务器,是禁⽌发送OPTIONS请求的,这样会导致跨域问题:
jquery-3.4.1.min.js:2 OPTIONS test/gtkjCghj/workflow/processes 401 (Unauthorized)
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
简单请求
只要同时满⾜以下条件就属于简单请求
1、请求⽅法是以下三种⽅法之⼀:GET、POST、HEAD
2、Http的头信息不超出以下⼏种字段:Accept、Accept-Language、Content-Language、Last-Event-ID、Content-Type。
Content-Type只限于三个值:application/x-www-form-urlencoded、multipart/form-data、text/plain
简单请求的请求头⽰例:
其中:Content-Type: application/x-www-form-urlencoded; charset=UTF-8
POST /gtkjCghj/workflow/processes HTTP/1.1
Host: aaa:7010
Connection: keep-alive
Content-Length: 212
ajax实例 文件浏览Accept: application/json, text/javascript, */*; q=0.01
Origin: 127.0.0.1:7010
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: 127.0.0.1:7010/gtkjCghj/static/cross.html
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
⾮简单请求,发送OPTIONS的请求头:
OPTIONS /gtkjCghj/workflow/processes HTTP/1.1
Host: aaa
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: aaa:7010
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: 127.0.0.1:7010/gtkjCghj/static/cross.html
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
总结:cors跨域请求解决⽅案(建议采⽤⽅案1)
1、springboot CORS 跨域请求解决三⼤⽅案,springboot CorsFilter解决跨域问题
2、cors-filter使⽤,cors-filter解决跨域访问,cors-filter跨域请求
3、org.ebaysf.web的cors-filter使⽤,cors-filter跨域请求
4、java tomcat-catalina CorsFilter使⽤,apache tomcat-catalina CorsFilter使⽤
5、springboot jsonp 跨域请求,springboot使⽤jsonp跨域
(如果⽂章对您有帮助,欢迎捐赠,^_^)
================================
©Copyright 蕃薯耀 2020-11-24

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。