在RestAngular请求中发送Cookie

时间:2016-09-19 11:01:38

标签: javascript angularjs spring cookies restangular

我有一个Restangular.getAll函数,

当我称之为Cookie时,Cookie不会包含在API请求中,与HTML请求不同。

如果我强迫:

Restangular.setDefaultHeaders({ Cookie: function() { return "foo " + $cookies.get('foo'); } })

错误是:

Refused to set unsafe header "Cookie"

如果我添加到app.config:

RestangularProvider.setDefaultHttpFields({
    withCredentials: true
});

错误是:

XMLHttpRequest cannot load [*link*] A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.
 Origin [*host*] is therefore not allowed access. 
The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

请注意,主机链接是页面链接和主机链接的缩写。

修改 我在春天的CORSFilter:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    public CORSFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        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, authorization, content-type");

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

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

1 个答案:

答案 0 :(得分:0)

您的服务器必须返回Access-Control-Allow-Origin的特定内容: 您可以在那里提供您的webapp主机URL,或动态复制原始信息(用于开发目的)。

注意:它是服务器端修复