0

I'm trying to get a json file from an api, when using this code on node.js it works perfectly fine and I can see the results I'm looking for, but when I try to use it from the browser it fails and returns with the error message on the title.

async function searchVolumes(volume, url, apiKey) {
  let result = await fetch(url, {mode: 'no-cors'})
    .then(res => res.json())
    .then(json => json.results)
    .catch(error => console.log('Error reading data ' + error))

  return result
}

I've tried it in Firefox and Edge and have the same problem in both of them, but checking the network tab I can see the result and the json is fine with no errors, and as I say at the beginning it works on node too.

lugDroid
  • 1
  • 2
  • Remove mode: 'no-cors'. See the answers at https://stackoverflow.com/questions/43317967/handle-response-syntaxerror-unexpected-end-of-input-when-using-mode-no-cors/43319482#43319482 and https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors/43268098#43268098 – sideshowbarker Nov 30 '18 at 20:33
  • OK thanks those answers are very helpful. I had it working previously with a proxy but I thought that was hacky and I was supposed not to use it, so I changed it to use the no-cors mode. Many thanks sideshowbarker. – lugDroid Dec 01 '18 at 09:00

1 Answers1

0

I modified it according to sideshowbarker links and removed the no-cors mode and added a proxy cors anywhere server and it's working now:

const proxy = 'https://cors-anywhere.herokuapp.com/'
url += proxy

async function searchVolumes(volume, url, apiKey) {
  let result = await fetch(url)
    .then(res => res.json())
    .then(json => json.results)
    .catch(error => console.log('Error reading data ' + error))

  return result
}
lugDroid
  • 1
  • 2