2

I'm working in a local project with vanilla js. I'm trying to get a json from a local file, but I get an error about the CORS Policy. I already tried with Ajax, Fetch API, and others, but I get the same error. So... It's posible to avoid this Policy with another option?

This is my code:

const loadFile = () =>{
    fetch("file.json")
    .then( response => response.json())
    .then( content => {
        console.log(content);
    })
}
Always Helping
  • 14,316
  • 4
  • 13
  • 29
Christian Elías
  • 41
  • 1
  • 2
  • 7

2 Answers2

0

You can use the JSONP (JSON with Padding) method for getting around the CORS restrictions.

luek baja
  • 1,475
  • 8
  • 20
0

To avoid CORS error issue just use this https://cors-anywhere.herokuapp.com/ and put your url after.

Local Enviroment => If you are using local environment you can simple { mode: 'no-cors'} to your fetch requests it should be all good.

Change your code to this. Should be fine.

const loadFile = () => { 
  //CORS URL
  let corsURL = 'https://cors-anywhere.herokuapp.com/';

  //My File URL
  let myURL = 'https://your_url.com/file.json';

  fetch(corsURL + myURL, { mode: 'no-cors'})
    .then(response => response.json())
    .then(content => {
      console.log(content);
    })
}

loadFile()
Always Helping
  • 14,316
  • 4
  • 13
  • 29