4

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'));

0

1 Answer 1

5

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...

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, just what I was looking for.
@umbe1987 Your last comment is good point to create NEW question in stack-overflow (because is different topic than your main question)
Really sorry to delete the comment just before your answer. Anyway, I thought the same so I'll probably post a new question if I don't find out myself a way to "return result" rather than "alerting it".
Ok, it seems cors-anywhere does not work with localhost. I should probably use a VPN to let cors-anywhere reach my computer.
Yes of course - third-party service usually will not "see" your localhost.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.