Fork me on GitHub

ajax跨域问题解决(spring boot)

之前用的服务器响应头部添加Access-Control-Allow-Origin: *来解决的

public static void setResp(HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
}

现在spring boot可以通过配置CorsRegistry来解决

@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**");
            }
        };
    }
}
posted @ 2017-03-20 16:15  cosyer  阅读(3778)  评论(0编辑  收藏  举报