请求的资源上不存在 'Access-Control-Allow-Origin' header。离子,AngularJS,Spring 启动 1.3

No 'Access-Control-Allow-Origin' header is present on the requested resource. Ionic, AngularJS, Spring Boot 1.3

我正在使用 Ionic 和 Spring Boot 1.3。直到我升级到 1.3,我才遇到这个问题...

显然是在更新到 Spring Boot 1.3 之后。 CorsFilter 被完全忽略。所有这些弃用都让我抓狂。所以我查找了新方法,这就是我得到的。

package app.config;

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

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://192.168.1.66:8101")
                .allowCredentials(false)
                .maxAge(3600)
                .allowedHeaders("Accept", "Content-Type", "Origin", "Authorization", "X-Auth-Token")
                .exposedHeaders("X-Auth-Token", "Authorization")
                .allowedMethods("POST", "GET", "DELETE", "PUT", "OPTIONS");
    }
}

以上代码在应用程序启动时执行。与每次有请求时执行的 CorsFilter 不同。但是切换到 Spring Boot 1.3,我无法再在链过滤器中得到它。

同样,正在加载代码,我设置了一个断点,并且每次都会调用 addCorsMapping,以便进行设置。所以....为什么我仍然收到此错误

XMLHttpRequest cannot load http://192.168.1.66:8080/login?username=billyjoe&password=happy. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.66:8101' is therefore not allowed access.

编辑 下面是我的旧 CorsFilter。它不再工作,因为我更新到 Spring Boot 1.3

package app.config;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CorsFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(CorsFilter.class);

    public CorsFilter() {
        log.info("SimpleCORSFilter init");
    }

    @Override
    public void doFilter(ServletRequest req,
                         ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String clientOrigin = request.getHeader("origin");
        response.addHeader("Access-Control-Allow-Origin", clientOrigin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET,  DELETE, PUT");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Origin, Authorization, X-Auth-Token");
        response.addHeader("Access-Control-Expose-Headers", "X-Auth-Token");

        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

你可以尝试这样的事情。它对我有用:.

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

想通了。我正在使用 CustomToken 登录,出于某种原因,在使用自定义登录身份验证时,1.3 及更高版本的新配置不会将响应设置为 Access-Control-Allow-Origin。因此,在我的自定义登录中的某处,我必须添加响应 header。

httpServletResponse.addHeader("Access-Control-Allow-Origin", "http://192.168.1.66:8080"); 

在 Spring 的旧版本中,CorsFilter 是在过滤器中设置的,因此每次调用时都会设置它。似乎新配置仅在正确调用控制器时才起作用,但由于登录是在过滤器而不是控制器中处理的,因此永远不会设置响应 body。它正确验证了用户 Access-Control-Allow-Origin

在我的开源项目中,在更新到 Spring 4.2 之前我需要 CORS 支持,我使用了这样的过滤器:

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

作为Raca的answare。但是,当我在 spring-boot 1.3.3 更新时,我更改了如下配置:

@SpringBootApplication
@Configuration
@EnableEurekaClient
@RibbonClients
@EnableCircuitBreaker
@EnableZuulProxy
@EnableJpaRepositories(basePackages = "it.valeriovaudi.documentlibrary.repository")
@EnableTransactionManagement
@EnableRedisHttpSession
@PropertySource("classpath:restBaseUrl.properties")
@EnableAspectJAutoProxy(proxyTargetClass = true) // without this declaration the RestTemplate injection wil be fails becouse spring cloud proxied this class for load balance with netflix ribbon
public class UserDocumentLibraryClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserDocumentLibraryClientApplication.class, args);
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurerSupport() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public EmbeddedServletContainerCustomizer exceptionHandling() {
        return container -> container.addErrorPages(new ErrorPage("/exception"));
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

这取自我的项目的主要配置,即使在使用 netflix api of Spring 云的复杂分布式系统中,这种配置对我来说也能很好地工作。

希望对您有所帮助