“访问控制允许来源:*”对 REST Web 服务没有影响
我从 JavaScript 客户端(在计算机 A 上运行)向 Web 服务器(在计算机 B 上运行)发出 AJAX 调用。 客户端尝试访问 RESTful Web 服务 (Jersey) 公开的 URL,但被阻止并出现错误:
来源 http://localhost/ 不是 允许的 访问控制允许来源
在服务器中,我添加了 2 个标头参数,允许访问任何客户端。然而它没有帮助:
@Context
private HttpServletResponse servlerResponse;
@POST
@Path("testme")
public void test(){
servlerResponse.addHeader("Access-Control-Allow-Origin", "*");
servlerResponse.addHeader("Access-Control-Allow-Credentials", "true");
}
相同的标头在 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>
我错过了什么吗?
谢谢
P.S 客户端部分是:
$.ajax({
type: "POST",
url: "http://localhost:8080/login/testme",
dataType: 'json',
success: onLoginSuccess,
error: onLoginError
});
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:
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");
}
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>
Am I missing something?
thanks
P.S the client part is:
$.ajax({
type: "POST",
url: "http://localhost:8080/login/testme",
dataType: 'json',
success: onLoginSuccess,
error: onLoginError
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为解决方案,我们实现了 javax.servlet.Filter,它将所需的标头添加到每个响应中:
As a solution, we implemented javax.servlet.Filter that adds required headers to every response:
@epeleg这是我做这样的事情的首选方法是过滤响应(Jersey 2.x):
@epeleg This is my preferred way of doing things like this is to do filtering of response (Jersey 2.x):