请求的资源上不存在 Access-Control-Allow-Origin 标头

2022-01-15 00:00:00 cors jquery javascript ajax java

我想访问来自同一个域但具有不同端口号的信息,为此我添加了 Access-Control-Allow-Origin 与响应标头.

I want to access information from same domain but with different port number, To allow this I am adding Access-Control-Allow-Origin with the response header.

Servlet 代码:(出现在 www.example.com:PORT_NUMBER 上)

Servlet Code:(present on 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)

jQuery code:(present on www.example.com)

$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'}).done(function(data)
{
    alert(data);
});

我多次收到此错误(在控制台中):

Several times I am getting this error(in console):

XMLHttpRequest cannot load 'http://www.example.com:PORT_NUMBER/MYSERVLET'
No 'Access-Control-Allow-Origin' header is present on the requested resource.

这个错误大多是在 $.post 被执行时第一次发生.第二次允许.

This error mostly occures first time when $.post gets executed. Second time it allows.

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

My question is that is there missing in servlet or in jQuery code?

任何建议将不胜感激.

更新1

我变了:

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

收件人:

response.setHeader("Access-Control-Allow-Origin", "http://www.example.com");

然后我在控制台中收到此错误:

Then I am getting this error in console:

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.

[注意:白名单和来源相同,但仍然报错.它有时有效,有时会出现上述错误.]

[Note: whitelist and origin are same, but still it gives error. It works sometimes, and gives above error sometimes.]

如果您需要更多信息,请告诉我.

Let me know if you need anymore information.

推荐答案

解决方案:
我没有使用 setHeader 方法,而是使用了 addHeader.

Solution:
Instead of using setHeader method I have used addHeader.

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

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

* in above line will allow access to all domains, For allowing access to specific domain only:

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

有关 IE<=9 的问题,请参阅 这里.

相关文章