使用 JSFiddle 测试提取 API - CORS 错误

testing fetch API with JSFiddle - CORS errors

我正在使用 JSFiddle 通过提取进行一些测试 API,但我每次都收到 CORS 源块。

有办法绕过吗?我正在获取的服务器是本地主机,我应该做些什么来接受 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'));

是的,有办法 - 你需要在服务器上允许 CORS

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

第三种方法:您可以使用一些现有的 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...