“Access-Control-Allow-Origin:*”对REST Web服务没有影响 [英] "Access-Control-Allow-Origin:*" has no influence in REST Web Service

查看:191
本文介绍了“Access-Control-Allow-Origin:*”对REST Web服务没有影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从JavaScript客户端(在机器A上运行)到Web服务器(在机器B上运行)进行AJAX调用。
客户端尝试访问RESTful Web服务(Jersey)公开的URL,并且阻止它出现错误:

I make an AJAX call from JavaScript client (running on machine A) to Web server (running on machine B). Client tries to access a URL exposed by RESTful Web service (Jersey), and it is blocked with error:


a href =http:// localhost /> http:// localhost / 不是
允许的
Access-Control-Allow-Origin

Origin http://localhost/ is not allowed by Access-Control-Allow-Origin

在服务器中,我添加了两个头参数,允许访问任何客户端。但它没有帮助:

In server I added 2 header parameters that allow access to any client. However it didn't help:

@Context
private HttpServletResponse servlerResponse;

@POST
@Path("testme")
public void test(){
    servlerResponse.addHeader("Access-Control-Allow-Origin", "*");
    servlerResponse.addHeader("Access-Control-Allow-Credentials", "true");
}

在JSP的情况下,同样的标题工作:

The same headers work in case of JSP:

<%
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Credentials", "true");
%>
<html>
<head><title>test jsp</title></head>
<body>
test
</body>
</html>

我错过了什么?

PS的客户端部分是:

P.S the client part is:

$.ajax({
    type: "POST",
    url: "http://localhost:8080/login/testme",
    dataType: 'json',
    success: onLoginSuccess,
    error: onLoginError
});


推荐答案

作为一个解决方案,我们实现了javax.servlet.Filter

As a solution, we implemented javax.servlet.Filter that adds required headers to every response:

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, java.io.IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    // This should be added in response to both the preflight and the actual request
    response.addHeader("Access-Control-Allow-Origin", "*");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.addHeader("Access-Control-Allow-Credentials", "true");
    }

    chain.doFilter(req, resp);
}

这篇关于“Access-Control-Allow-Origin:*”对REST Web服务没有影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆