前后端分离跨域问题汇总CORS
一、跨域通信的问题,即CORS。默认会403
1、现象:前端调用会报错“has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource”,后端收不到请求。
2、方案,后端设置:Access-Control-Allow-Origin
2.1 springboot2的话,可以设置:
2.1.1 接口类或方法注解的方式
@CrossOrigin
2.1.2 拦截器的方式
package com.order.config; import com.google.common.collect.Lists; 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 java.util.List; /** * 实现基本的跨域请求 */ @Configuration public class GlobalCorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); List<String> allowedOriginList = Lists.newArrayList(); allowedOriginList.add("http://localhost:3000"); allowedOriginList.add("http://localadmain.com"); corsConfiguration.setAllowedOrigins(allowedOriginList); // corsConfiguration.addAllowedOrigin(allowedOriginList); // 允许任何域名使用 corsConfiguration.setAllowCredentials(true); corsConfiguration.addAllowedHeader("*"); // 允许任何头 corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等) return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置 return new CorsFilter(source); } }
二、登录状态保持的问题
处理了问题一,后面的ajax请求还会有401的问题,因为丢失了登录状态。方案有:
1、共享cookie的方式。
前端:
<script> $(function () { $.ajax({ url : "http://www.b.com:8888/test/setCookie", method: "get", success : function (json) { console.log(json); }, xhrFields: { withCredentials: true } }); }) </script>
后端:
@CrossOrigin(origins="http://www.a.com:8888",allowCredentials = "true")
或
CorsConfiguration corsConfiguration = new CorsConfiguration(); List<String> allowedOriginList = Lists.newArrayList(); allowedOriginList.add("http://localhost:3000"); allowedOriginList.add("http://localadmain.com"); corsConfiguration.setAllowedOrigins(allowedOriginList); // corsConfiguration.addAllowedOrigin(allowedOriginList); // 允许任何域名使用 corsConfiguration.setAllowCredentials(true);
2、token的方式:
可以自己实现,也可以借助:
jwt
oauth2
z
相关推荐
yiranpiaoluo 2020-11-04
yyyxxxs 2020-06-26
Chydar 2020-05-16
ysmh00 2020-05-14
yuxinshuier 2020-04-21
wolfjin 2020-04-21
fengchao000 2020-04-11
somebodyoneday 2020-03-06
Strongding 2020-01-14
zagnix 2019-11-16
wenf00 2019-11-04
baijinswpu 2019-10-31
wsd 2015-05-29
adonislu 2019-09-08
HAcSeeking 2018-11-05
chenchuanwen 2019-05-24
haocxy 2014-08-21
sunyu0 2019-06-29