用于Spring和Angular的CORS过滤器不起作用

时间:2016-06-18 18:17:44

标签: java spring-security http-headers cors cross-domain

我有两个项目。首先是春季休息后端,第二个是angularjs应用程序。它们在不同的服务器和端口上运行

REST application, using spring, http://localhost:8081
HTML application, using angularjs, http://localhost:63342

angularJs api调用非常简单

registerController.factory('registerFactory', function(){
    return {
        getClassification:function($http,tempString){
            //TODO add URL
            var url = "http://localhost:8081/example?eg="+tempString
            return $http({
                method: 'POST',
                url: url
            });
        }
    }
});

弹簧控制器看起来像

@CrossOrigin(origins = "http://localhost:63342")
@RequestMapping(value = "/example", method = RequestMethod.POST)
@ResponseBody
public String postAppUser(@RequestParam String eg) throws JsonProcessingException {
        String ka = eg;
        System.out.println("asdasd");
        return "ok yes ";           
}

CORS过滤器看起来像

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.springframework.stereotype.Component;

@Component
public class CORSFilter implements Filter {

    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);
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}

web.xml看起来像

<web-app>
  <display-name>Archetype Created Web Application</display-name>  
</web-app>

每次调用其余的api我都会收到以下错误

XMLHttpRequest cannot load http://localhost:8081/example?eg=as. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 404.

我刚开始参与一个项目。这是我尝试登录/注册用户的第一阶段。

0 个答案:

没有答案