Springcloud REST API 接口调用时出现跨域问题,服务端解决办法

1、首先 定义一个过滤区。

public class PathFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response ;
        resp.setHeader("Access-Control-Allow-Methods", "*");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Credentials","true");
        chain.doFilter(request,response);        
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }
    
}

2、然后, 将此过滤器注册到FilterRegistrationBean当中

@Configuration
public class PathConfig {
    @Bean
    public FilterRegistrationBean pathFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new PathFilter());
        registration.addUrlPatterns("/*");
        registration.setName("PathFilter");
        registration.setOrder(1);
        return registration;
    }
}

此时,API接口调用成功。

 

同时还可以使用org.springframework.web.bind.annotation.CrossOrigin

@CrossOrigin注解解决跨域问题。

你可能感兴趣的:(Springcloud REST API 接口调用时出现跨域问题,服务端解决办法)