Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - No Access-Control-Allow-Origin header is present on the requested resource

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

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

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

Any suggestion will be appreciated.

Update1

I have changed:

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

To:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

For issues related to IE<=9, Please see here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...