目录
Credentials
编辑
问题一
问题二
问题三
解决方法一 CrossOrigin,最优的方法
解决方法二 通过Filter 设置HTTP
解决方法三 通过实现WebMvcConfigurer设置HTTP
解决方法四 通过CorsFilter
Access-Control-Allow-Headers authorization 问题
解决办法,服务器添加authorization
HTTP 协议,需要认真的学习每个细节。
allowCredentials(true) 和 allowed-origins: "*" 不能同时配置
allowCredentials(true) 和 allowed-origins: "http://127.0.0.1:5500" 匹配
Credentials
Credentials告诉brower 带上Cookie信息,这时Allow-Origin不能是wildcard(*)。
因为* 可能造成网站的不安全,不会把Cookie给任何请求,所以Allow-Origin必须有值。
Credentials=false时,Set-Cookie不会生效。
问题一
No 'Access-Control-Allow-Origin',此错误信息不准确,配置的信息里任何一项有错误,都会报如下信息。如果addmapping("/rest")会报这个错误,准确的是addmapping("/rest/**")。
Access to fetch at 'http://localhost:8888/rest/order/1' from origin 'http://127.0.0.1:5500' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
问题二
"When allowCredentials is true, allowedOrigins cannot contain the special value \"*\" since that cannot be set on the \"Access-Control-Allow-Origin\" response header. To allow credentials to a set of origins, list them explicitly or consider using \"allowedOriginPatterns\" instead."
//.allowCredentials(true)
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:5500")
//.allowCredentials(true)
.allowedMethods(yml.WEB_CORS_ALLOWED_METHODS)
.maxAge(yml.WEB_CORS_MAX_AGE)
.allowedHeaders(yml.WEB_CORS_EXPOSED_HEADERS)
.exposedHeaders(yml.WEB_CORS_EXPOSED_HEADERS);
WebMvcConfigurer.super.addCorsMappings(registry);
}
问题三
请求过程中出现异常,导致没有正常的返回,Response的Header没有数据,也会出现CORS,
需要让请求正常返回。
解决方法一 CrossOrigin,最优的方法
最简单实现跨域访问的方法是通过注释@CrossOrigin。
@CrossOrigin
@GetMapping("/order/{id}")
public OrderVO getOrder(@PathVariable("id") Long id,
HttpServletRequest request,
HttpServletResponse response) {
}
解决方法二 通过Filter 设置HTTP
@Component
public class WebCommonFilter implements Filter{
/**
* handle CORS question by {@link HttpServletRequest}
& {@link HttpServletResponse} ,
* This method can resolve any CORS by setting
Access-Control-Allow-Origin = true
* or Access-Control-Allow-Origin = req.getHeader("Origin").
*/
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String curOrigin = req.getHeader("Origin");
HttpServletResponse res = (HttpServletResponse) response;
res.setHeader("Access-Control-Allow-Origin",
curOrigin == null ? "true" : curOrigin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "POST,
GET, OPTIONS, DELETE, HEAD");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers",
"access-control-allow-origin, x-custom-header,authority,
content-type, version-info, X-Requested-With");
res.setContentType("application/json;charset=UTF-8");
chain.doFilter(req, res);
}
}
解决方法三 通过实现WebMvcConfigurer设置HTTP
最灵活的实现方式,推荐在项目中使用这种方式。
@Configuration
public class WebBaseMvcConfigurer implements WebMvcConfigurer {
@Autowired
WebConfigurerFromYML yml;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping(yml.mapping)
.allowedOrigins(yml.WEB_CORS_ALLOWED_ORIGINS)
.allowCredentials(true)
.allowedMethods(yml.WEB_CORS_ALLOWED_METHODS)
.maxAge(yml.WEB_CORS_MAX_AGE);
// .allowedHeaders(yml.WEB_CORS_ALLOWED_HEADERS);
// .exposedHeaders(yml.WEB_CORS_EXPOSED_HEADERS);
}
}
web:
cors:
mapping: "/rest/**"
allowed-origins: "http://127.0.0.1:5500"
allowed-methods: "POST,GET,OPTIONS,DELETE,HEAD"
max-age: 3600
allowed-headers: "access-control-allow-origin"
exposed-headers: "X-Get-Header"
解决方法四 通过CorsFilter
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1. 添加 CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//放行哪些原始域
config.addAllowedOrigin("http://localhost:8080/");
//是否发送 Cookie
config.setAllowCredentials(true);
//放行哪些请求方式
config.addAllowedMethod("*");
//放行哪些原始请求头部信息
config.addAllowedHeader("*");
//暴露哪些头部信息
config.addExposedHeader("*");
//2. 添加映射路径
UrlBasedCorsConfigurationSource corsConfigurationSource
= new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**",config);
//3. 返回新的CorsFilter
return new CorsFilter(corsConfigurationSource);
}
}
Access-Control-Allow-Headers authorization 问题
Access-Control-Allow-Headers 允许的参数没有包含客户端请求的参数,如authorization。然后会出现CORS跨域问题。
文章来源:https://www.toymoban.com/news/detail-470200.html
解决办法,服务器添加authorization
文章来源地址https://www.toymoban.com/news/detail-470200.html
到了这里,关于SpringBoot3 CORS跨域访问的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!