没有访问控制 - 允许 - 产地标头的请求的资源present [英] No Access-Control-Allow-Origin header is present on the requested resource

查看:350
本文介绍了没有访问控制 - 允许 - 产地标头的请求的资源present的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从同一个域,但具有不同的端口号访问信息,为实现这一点我加入访问控制 - 允许 - 原产地的响应头。

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:($ P $上www.example.com:PORT_NUMBER psent)

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:($ P $在www.example.com psent)

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.

此错误大多occures当 $。交被执行的第一次。第二次允许。

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

我的问题是,是否有失踪的servlet 的jQuery code?

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

任何建议将AP preciated。

Any suggestion will be appreciated.

UPDATE1

我已经改变了:

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,请参阅<一href="http://stackoverflow.com/questions/10232017/ie9-jquery-ajax-with-cors-returns-access-is-denied">here.

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

这篇关于没有访问控制 - 允许 - 产地标头的请求的资源present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆