添加CORS过滤器后找不到Access-Control-Allow-Origin标头

时间:2016-04-29 20:11:55

标签: spring-boot http-headers xmlhttprequest cors

我使用AngularJS实现了一个用于用户身份验证的登录表单。以下是我的邮寄请求登录服务:

app.factory("loginFactory", function ($http) {
    return{
        login: function(username, password) {
            var data = "username="+username+"&password="+password+"&submit=Login";
            return $http({
                method: 'POST',
                url: 'http://localhost:8080/login',
                data: data,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            });  
        }
    }   
});

运行时出现以下错误。

XMLHttpRequest cannot load http://localhost:8080/login.No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access.

我做了一些研究,发现必须在服务器端添加标题。根据此post,我将以下内容添加到我的Rest Service

@Component
public class SimpleCORSFilter implements Filter {

    @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() {
    }
}

但是,我仍然遇到同样的错误。

1 个答案:

答案 0 :(得分:3)

由于浏览器在允许原始标题中查找response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8081"); ,因此您需要确保在以下行中添加此内容:

http://127.0.0.1:8081

要获得request.getRemoteAddr() + ":" + request.getRemotePort(); ,您可以使用:

request.getRemoteHost().

但是如果浏览器寻找localhost,那么请转到:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"

print(birthday)  

let date = dateFormatter.dateFromString(birthday)
self.datePicker.setDate(date!, animated: true)

希望能解决你的问题。