可扩展应用程序的CORS问题

CORS issue for Scalable application

本文关键字:问题 CORS 应用程序 可扩展      更新时间:2023-09-26

我在AngularJS中有三个应用程序,其次是authserver,资源服务器和前端应用程序。AngularJS应用程序运行在Node Server上,其他资源运行在Tomcat Server上。通过使用CORS的AngularJS,我能够登录到authserver (http://localhost:8081/oauth/token),我无法访问资源服务器(http://localhost:8082/api/devices)。标题是这样添加的:

var config = {
    headers: {
        'Authorization': 'bearer '+authToken,
        'Accept': 'application/json;odata=verbose'
    }
};
$http.get(RESOURCE_SERVER + 'api/devices',config).then(function(response){
    console.log(""+response.data);
});'''

报头没有添加到资源服务器并获得异常,如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, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }
    public void init(FilterConfig filterConfig) {}
    public void destroy() {}
}

错误:: XMLHttpRequest不能加载http://192.168.0.130:8080/golive-resource/api-docs。的'Access-Control-Allow-Origin'标头包含多个值'*,*',但只允许一个。因此,起源'http://127.0.0.1:9000'是不允许访问

问题在于,在您的设置的其他地方,您也设置了Access-Control-Allow-Origin标头,而不是一个覆盖另一个,它们由服务器组合,这意味着您最终有两个值。

有两个报头值将导致错误。因此,你应该找出你在其他地方设置了这个头,或者删除该实例,或者从上面的代码片段中删除它。

实际上浏览器在您的实际请求之前使用http请求方法"options"进行预飞行请求。所以你必须给这个请求发送200ok

if(httpRequest.getMethod().equals("OPTIONS")){
        httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }

更多信息请访问http://enable-cors.org/