Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing fetch API with JSFiddle - CORS errors [duplicate]

I am using JSFiddle to make some tests with the fetch API, but I am getting CORS origin block everytime.

Is there a way to bypass it? The server I am fetching is localhost, should I do something to accept requests by JSFiddle or is there an easier way to do it witout touching my server configuration?

Here is an example:

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'));
like image 242
umbe1987 Avatar asked Oct 19 '25 01:10

umbe1987


1 Answers

Yes there is a way - you need to allow CORS on SERVER

Another approach: If you cannot allow CORS on third-party server, you can write your own CORS-ON-SERVER (proxy) which will connect with third-party server and send/receive data from it.

Third approach: You can use some existing cors-proxy server like this and use it for example - change line:

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

to

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...
like image 60
Kamil Kiełczewski Avatar answered Oct 20 '25 14:10

Kamil Kiełczewski