【问题标题】:testing fetch API with JSFiddle - CORS errors [duplicate]使用 JSFiddle 测试 fetch API - CORS 错误 [重复]
【发布时间】:2018-10-24 00:41:10
【问题描述】:

我正在使用 JSFiddle 对 fetch API 进行一些测试,但每次都会收到 CORS 源块。

有没有办法绕过它?我正在获取的服务器是 localhost,我应该做些什么来接受 JSFiddle 的请求还是有一种更简单的方法可以在不触及我的服务器配置的情况下做到这一点?

这是一个例子:

async function getText(url) {
  try{
    var response = await fetch(url);
    var txt = await response.text();
    return txt;
  }
  catch(e){
    console.log('there was an error');
    console.log(e); 
  }
}

alert(getText('https://www.vim.org/git.php'));

【问题讨论】:

    标签: javascript cors cross-domain fetch jsfiddle


    【解决方案1】:

    是的,有一种方法 - 您需要在 SERVER 上允许 CORS

    另一种方法:如果您不能在第三方服务器上允许 CORS,您可以编写自己的 CORS-ON-SERVER(代理),它将与第三方服务器连接并从中发送/接收数据。

    第三种方法:您可以使用一些现有的 cors-proxy 服务器,例如 this 并使用它 - 换行:

    alert(getText('https://www.vim.org/git.php'));
    

    async function run() {
      let result = await getText('https://cors-anywhere.herokuapp.com/https://www.vim.org/git.php');
      alert(result);
    }
    
    run();
    

    async function getText(url) {
      try{
        var response = await fetch(url);
        var txt = await response.text();
        return txt;
      }
      catch(e){
        console.log('there was an error');
        console.log(e); 
      }
    }
    
    async function run() {
      let result = await getText('https://cors-anywhere.herokuapp.com/https://www.vim.org/git.php');
      document.body.innerHTML=result;
      //  alert(result);
    }
    
    run();
    wait...

    【讨论】:

    • 谢谢,正是我想要的。
    • @umbe1987 您的最后一条评论是在堆栈溢出中创建新问题的好点(因为主题与您的主要问题不同)
    • 真的很抱歉在您回答之前删除评论。无论如何,我也是这么想的,所以如果我找不到“返回结果”而不是“提醒它”的方法,我可能会发布一个新问题。
    • 好吧,似乎 cors-anywhere 不适用于 localhost。我可能应该使用 VPN 让 cors-anywhere 访问我的计算机。
    • 当然可以——第三方服务通常不会“看到”你的本地主机。
    猜你喜欢
    • 2018-12-03
    • 1970-01-01
    • 2019-04-12
    • 2014-01-10
    • 2021-09-03
    • 1970-01-01
    • 2017-03-23
    • 2020-10-09
    • 2021-07-27
    相关资源
    最近更新 更多