淘先锋技术网

首页 1 2 3 4 5 6 7

微服务架构经常会用到跨服务器之间调用,这就牵涉到跨域问题,springboot项目有三种方法解决跨域问题,

1  增加过滤器拦截并给请求增加header信息
 

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

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

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
 
		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;
		response.setHeader("Access-Control-Allow-Origin", "*");//源网址 
		response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE, HEAD");
		response.setHeader("Access-Control-Allow-Headers", "x-auth-token, x-requested-with, Content-Type");
		response.setHeader("Access-Control-Max-Age", "3600");

		if (!"OPTIONS".equals(request.getMethod())) {
			chain.doFilter(req, res);
		} else {
		}
	}

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

	}

}

2 继承WebMvcConfigurerAdapter并重写addCorsMappings方法
 


@Configuration
public class MvcConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*")
                //origin 允许访问的链接来自
                .allowedOrigins("http://www.baidu.com").allowedHeaders("*");
    }

}

 

 

3 controller类上加@CrossOrigin注解

@CrossOrigin
@Controller
public class TestController {
 
    @RequestMapping(value = "/coos")
    @ResponseBody
    public String test() {

        return "this is core info ";
    }

}

这样springboot的项目就支持跨域访问了,有什么不对的地方欢迎指正