SpringBoot开发的API解决跨域访问问题

2021-08-18 867点热度 0人点赞 0条评论

我们用SpringBoot写好的Rest API,在开发阶段,前后端联调的时候,发现前端写的例如vue程序(axios)无法连接API,通过浏览器日志发现报错:No 'Access-Control-Allow-Origin' header is present on the requested resource.

原因是跨域了,为了安全期间,前端的程序和API不是同一个URL,导致无法访问。

网上写的一些SpringBoot解决跨域的,是给Controller增加@CrossOrigin注解,或者配置WebMvcConfigurerAdapter增加addCorsMappings

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")  // 拦截所有的请求
            .allowedOrigins("*")  // 可跨域的域名,可以为 *
//           .allowCredentials(true)
            .allowedMethods("*")   // 允许跨域的方法,可以单独配置
            .allowedHeaders("*");  // 允许跨域的请求头,可以单独配置
}

以上这些都无效,客户端访问,提示:

Access to XMLHttpRequest at 'http://192.168.1.1:8081/login' from origin 'http://192.168.1.1:8081' 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.

也就是说没有Access-Control-Allow-Origin这个header,而实际去查这个API返回的header,只是增加了这个Header:

Vary
Origin, Access-Control-Request-Method, Access-Control-Request-Headers

所以可以这样做,自定义一个拦截器,在需要的请求的header里增加Access-Control-Allow-Origin

新建拦截器 CorsInterceptor.java

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CorsInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,X-CAF-Authorization-Token,sessionToken,token,X-TOKEN");
        response.addHeader("Access-Control-Max-Age", "3600");
        return true;
    }
}

配置拦截器

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CorsInterceptor()).addPathPatterns("/api/**");
        super.addInterceptors(registry);
    }

}

 

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论