小编典典

请求的资源上没有Access-Control-Allow-Origin标头

ajax

我想访问来自同一域但端口号不同的信息,为此,我添加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在执行时首次发生。第二次允许。

我的问题是代码中servletjQuery代码中缺少什么?

任何建议将不胜感激。

更新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.

[注意:白名单和来源相同,但仍然会出错。有时会起作用,有时会出现上述错误。]

让我知道您是否需要更多信息。


阅读 310

收藏
2020-07-26

共1个答案

小编典典

解决方案 :我没有
使用setHeader方法addHeader

response.addHeader("Access-Control-Allow-Origin", "*");

* 上一行中的允许访问所有域,仅允许访问特定域:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
2020-07-26