使用 JSFiddle 测试 fetch API - CORS 错误

umb*_*987 4 javascript cross-domain fetch cors jsfiddle

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

有办法绕过它吗?我正在获取的服务器是 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'));
Run Code Online (Sandbox Code Playgroud)

Kam*_*ski 5

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

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

第三种方法:您可以像这样使用一些现有的 cors-proxy 服务器并使用它 - 更改行:

alert(getText('https://www.vim.org/git.php'));
Run Code Online (Sandbox Code Playgroud)

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

run();
Run Code Online (Sandbox Code Playgroud)

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

run();
Run Code Online (Sandbox Code Playgroud)