【发布时间】:2014-01-19 19:37:01
【问题描述】:
我想访问来自同一个域但具有不同端口号的信息,为此我添加了Access-Control-Allow-Origin 和响应头。
Servlet 代码:(出现在 www.example.com:PORT_NUMBER 上)
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");//cross domain request/CORS
response.getWriter().write(json);
jQuery 代码:(出现在 www.example.com)
$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'}).done(function(data)
{
alert(data);
});
我多次收到此错误(在控制台中):
XMLHttpRequest cannot load 'http://www.example.com:PORT_NUMBER/MYSERVLET'
No 'Access-Control-Allow-Origin' header is present on the requested resource.
这个错误主要是在$.post 被执行时第一次发生。第二次允许。
我的问题是servlet 或jQuery 代码中是否缺少?
任何建议将不胜感激。
更新1
我变了:
response.setHeader("Access-Control-Allow-Origin", "*");
收件人:
response.setHeader("Access-Control-Allow-Origin", "http://www.example.com");
然后我在控制台中收到此错误:
XMLHttpRequest cannot load http://www.example.com:PORT_NUMBER/MyServletName
The 'Access-Control-Allow-Origin' whitelists only 'http://www.example.com'
Origin 'http://www.example.com' is not in the list,
and is therefore not allowed access.
[注意:白名单和来源相同,但仍然报错。它有时有效,有时会出现上述错误。]
如果您需要更多信息,请告诉我。
【问题讨论】:
-
这很简单:您的服务器响应不包含正确的 CORS 标头。这不是浏览器错误,也没有客户端代码问题。如果您想深入了解这一点,请更仔细地跟踪您的服务器端代码,以确保标头始终包含在响应中。您应该首先在客户端和服务器之间插入一个代理来自己检查标头。
标签: javascript java jquery ajax cors