V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
leosirius666a
V2EX  ›  程序员

跨域请求的一个问题

  •  
  •   leosirius666a · 2019-12-22 14:28:40 +08:00 · 2704 次点击
    这是一个创建于 1578 天前的主题,其中的信息可能已经有所发展或是发生改变。

    自己用 XHR 对象向 google.com 发起 get 请求,浏览器会报

    Access to XMLHttpRequest at 'https://www.google.com/' from origin 'http://localhost:52331' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    

    我用浏览器直接访问 google.com ,不也是在不同的域吗,为什么没有跨域问题。

    16 条回复    2019-12-22 21:49:21 +08:00
    lhx2008
        1
    lhx2008  
       2019-12-22 14:30:35 +08:00
    不要带自定义头
    lhx2008
        2
    lhx2008  
       2019-12-22 14:31:27 +08:00
    说错了,这种 Google 回的时候要有一个额外的头
    leosirius666a
        3
    leosirius666a  
    OP
       2019-12-22 14:31:56 +08:00
    我什么都没做,代码这样的
    ```js
    let xhr = new XMLHttpRequest();
    xhr.open("get", "https://www.google.com", true);
    xhr.send(null);

    xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
    alert(xhr.responseText);
    } else {
    alert("Request was unsuccessful: " + xhr.status);
    }
    }
    }
    ```
    1OF7G
        4
    1OF7G  
       2019-12-22 14:32:27 +08:00
    这是浏览器对网页施加的限制,而不是 系统或网络协议或某种魔法 对浏览器的限制。
    leosirius666a
        5
    leosirius666a  
    OP
       2019-12-22 14:34:24 +08:00
    @1OF7G 我知道是浏览器在 response 成功返回后浏览器自己把返回 block 了,但是为什么直接访问它就没有 block
    1OF7G
        6
    1OF7G  
       2019-12-22 14:42:01 +08:00
    @leosirius666a 浏览器只是阻止把 google.com 的内容给到其它第三方网站的 JS,如你的 localhost。如果你直接访问,根本没有第三者参与进来,还防范谁呢?
    beastk
        7
    beastk  
       2019-12-22 14:48:41 +08:00 via iPhone
    js 限制
    VDimos
        8
    VDimos  
       2019-12-22 14:53:34 +08:00 via Android
    。。。跨域不是这个意思,跨域是指你的域名的脚本加载了不是你域名的内容。。。
    leosirius666a
        9
    leosirius666a  
    OP
       2019-12-22 15:03:08 +08:00
    @VDimos 原来是这样。。
    cst4you
        11
    cst4you  
       2019-12-22 16:18:45 +08:00
    leosirius666a
        12
    leosirius666a  
    OP
       2019-12-22 16:32:21 +08:00
    ssshooter
        13
    ssshooter  
       2019-12-22 16:50:44 +08:00
    x66
        14
    x66  
       2019-12-22 20:37:01 +08:00
    “chrome.exe” –disable-web-security –user-data-dir=xxx
    beastk
        15
    beastk  
       2019-12-22 21:43:34 +08:00 via iPhone
    其实你还没搞懂。localhost 是本地域,有特权,不信你用 ie 使用 ajax,http https 是网络域,脚本资源遵循同源策略。
    beastk
        16
    beastk  
       2019-12-22 21:49:21 +08:00 via iPhone
    @beastk #15 勘误,在 ie 下,file 协议有特权
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5664 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 03:28 · PVG 11:28 · LAX 20:28 · JFK 23:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.