【问题标题】:Why this same-origin policy error on same domain?为什么在同一个域上出现同源策略错误?
【发布时间】:2013-11-28 02:51:34
【问题描述】:

在发布新网站前不久,我们发现计算机中的同源策略限制了对同一、源或域上的页面的访问。这是网站:http://blanc-encens.com/

更糟糕的是,如果它不能立即运行,在重新加载后它会运行!!

您能否从理论上告诉我为什么会发生这种情况,或者如果您是被选中的少数人中的一员,在哪里不起作用,请检查问题?编辑:我现在手动将标题设置为“*”!

Chrome 控制台错误:

XMLHttpRequest cannot load http://blanc-encens.com/profile?ajax=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.blanc-encens.com' is therefore not allowed access. profile:1 0 core.js:271

在 Chrome 中,在不工作的机器上的网络选项卡中没有 Response Headers

我的代码:

var hyper = {
    init : function() {
        this.content($('.navigation a').not('.follow a'));
        this.pop();
    },

    content : function(obj) {
        obj.on('click', function(e){
            var thisUrl = $(this).attr('href');
                thisalt = $(this).attr('alt');
            hyper.load(thisUrl);
            e.preventDefault;
            window.history.pushState(null, thisalt, thisUrl);
            document.title = thisalt;
        });
    },

    pop : function() {
        window.onpopstate  = function() {
            hyper.load(location.pathname);
        };

    },

    load : function(page) {
        page = page == '/' ? '/start' : page;
        $.ajax({
            type: 'GET',
            url: page, 
            data: {ajax : 1},
            success: function(data) {
            $('.content').empty().append(data);
            }
        });
    }
};
hyper.init();

谢谢!!

【问题讨论】:

  • 你有从blanc-encense.com切换到www.blanc-encens.com的代码吗?就浏览器而言,它们是不同的域。
  • @Barmar 这听起来很有希望。但真正让你头疼的事情是,在重新加载后,它在任何地方都能正常工作!!!
  • 脚本缓存可能吗?
  • @KevinB 这是怎么做到的?还是撤销? ;) 你的意思是将$.ajax 设置为cache: false
  • 不,我指的是之前的评论,你说它现在正在工作。如果它现在可以工作并且您没有更改任何内容,那么您的 javascript 被缓存了,或者您有竞争条件。 ajax 缓存可能与它无关。

标签: ajax xmlhttprequest same-origin-policy


【解决方案1】:

我现在带着我认为在这种情况下的“竞争条件”回来了。 Barmar 在他的第一条评论中一针见血,感谢 KevinB 这么长时间一直陪伴我并为我整理好一切。 ;)

.htaccess中的行

RewriteCond %{HTTP_HOST} ^www\.blanc-encens\.com
RewriteRule (.*) http://blanc-encens.com/$1 [R=301,L]

Javascript 中的旧行

var thisUrl = 
location.host == 'blanc-encens.com' 
? '/test' + $(this).attr('href') 
: $(this).attr('href');  
  • 现在有人给出了前面带有www的链接,这个脚本显然没有准备好。
  • 所以竞争条件一定是在.htaccess 中没有工作(有人听说过吗?),或者不够快。
  • 当有人打开页面时,它当然总是开始,但在第一次点击链接时,就会出现明显的混乱。
  • .htaccess 首先没有工作或不够快,然后有人点击了一个链接,Javascript 决定没有blanc-encens.com;您可以在错误消息中看到,网址中没有 /test
  • 然后.htaccess 开始了。
  • 瞧,您尝试从www 域切换到没有-www 域。 Bumm,同源策略错误。 ;)

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 2017-01-05
    • 1970-01-01
    • 2011-12-26
    • 2013-05-17
    • 2019-04-17
    • 2014-06-05
    • 2012-07-01
    • 2013-04-12
    相关资源
    最近更新 更多