在Spring Boot后端/ Angularjs前端应用程序中允许多个交叉起源?

时间:2017-06-20 08:14:09

标签: angular spring-boot configuration

我在目前正在处理的Web应用程序中收到以下错误:ErrorCode:

  

XMLHttpRequest无法加载http://rev-final.staging.cashu.com:8080/merchants/signup。 'Access-Control-Allow-Origin'标头包含多个值'*,*',但只允许一个。因此,不允许原点“http://localhost:3000”访问。

所以我该怎么做才能解决这个问题,解决方案必须来自角度方面或Spring Side,因为我在寻找解决方案时都在寻找配置

1 个答案:

答案 0 :(得分:1)

只需在组件扫描包中添加以下类,然后春天就会注意一切。请参考here以获取更多参考..

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 SimpleCORSFilter implements Filter {

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

public SimpleCORSFilter() {
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;

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}