SpringBoot3 CORS跨域访问

 

目录

Credentials

问题一

问题二

解决方法一 CrossOrigin,最优的方法

 解决方法二 通过Filter 设置HTTP

解决方法三 通过实现WebMvcConfigurer设置HTTP

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不会生效。

SpringBoot3 CORS跨域访问_第1张图片

问题一

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);
	}

解决方法一 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"   

你可能感兴趣的:(Spring,servlet,java,前端,CORS,springboot)