springboot跨域的处理方式

问题描述:

当请求服务器发送HTTP请求到目标服务器时,如果目标服务器的(协议、域名、端口)与请求服务器(协议、域名、端口)其中一个不同,就会出现跨域异常。

 

解决方法:

1、在applicatio.properties中配置可以访问的域;

#配置访问的域 
cors.origin
=*

 

2、然后创建跨域过滤器,在跨域过滤器设置跨域响应头以及可以访问的域;

import org.springframework.beans.factory.annotation.Value;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CrossOriginFilter implements Filter {

    @Value("${cors.origin}")
    private String origin;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws
IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        httpResponse.setHeader("Access-Control-Allow-Methods", httpRequest.getMethod());
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-ControlRequest-Headers"));
        chain.doFilter(request, response);
   }
}

 

3、接着编写跨域配置文件

    @Bean
    public CrossOriginFilter crossOriginFilter(){
        return new CrossOriginFilter();
   }

    @Bean
    public FilterRegistrationBean getFilterRegistrationBean(){
        FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
        // 设置过滤器
        filterRegistrationBean.setFilter(crossOriginFilter());
        // 拦截路径,以api开头的都会被拦截
        filterRegistrationBean.addUrlPatterns("/api/*");
        // 设置名称
        filterRegistrationBean.setName("CrossOriginFilter");
        return filterRegistrationBean;
   }

 

 

posted @ 2020-09-18 12:30  xueheng_blog  阅读(213)  评论(0编辑  收藏  举报