gpt4 book ai didi

rest - "Access-Control-Allow-Origin:*"对 REST Web 服务没有影响

转载 作者:行者123 更新时间:2023-12-03 22:48:17 25 4
gpt4 key购买 nike

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

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

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

@Context
private HttpServletResponse servlerResponse;

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

相同的 header 适用于 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
});

最佳答案

作为解决方案,我们实现了 javax.servlet.Filter,它向每个响应添加所需的 header :

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

关于rest - "Access-Control-Allow-Origin:*"对 REST Web 服务没有影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5406350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com