2

I'm trying to get product information from the Bol.com open api (dutch webshop) through the following code.

const config = {
  mode: 'cors',
  headers: {
    'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token'
  }
};

axios.get(productUrl, config)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

When trying to run this code on my website or localhost I'm getting the following errors.

enter image description here

The link is correct (If I open the link in another tab I'm getting a json object with all the product data) so I think it's something with cors.

After seeing this post Response to preflight request doesn't pass access control check I turned off my CORS in Google Chrome and I was able to receive the requested data.

However I can't ask everybody to turn off cors so I would really like to know how I can solve this problem with code. Anyone can help me out?

Thore
  • 1,225
  • 1
  • 11
  • 30
  • You need to remove all the `headers` key and value from your config object. All those `Access-Control-Allow-*` headers are *response* headers for servers to send. The only effect you’re going to see from sending them as request headers from your frontend JavaScript code is that they will trigger the browser to do automatically do a CORS preflight OPTIONS request that’s very likely going to fail. And when that OPTIONS preflight fails, the browser stops right there and never moves on to sending the GET request from your code. – sideshowbarker Aug 26 '17 at 11:47
  • Without the headers I'm still getting an Access-Control-Allow-Origin error: `No 'Access-Control-Allow-Origin' header is present on the requested resource.` – Thore Aug 26 '17 at 11:52
  • 1
    Yeah that means that `api.bol.com` API endpoint doesn’t send the `Access-Control-Allow-Origin` response header. So your only solutions are to either set up a CORS proxy using code from https://github.com/Rob--W/cors-anywhere/ or such, or make the request through an open CORS proxy like https://cors-anywhere.herokuapp.com/, or else make the request from your own backend code instead of from your frontend code. – sideshowbarker Aug 26 '17 at 11:54
  • For a more-detailed explanation, see https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141 – sideshowbarker Aug 26 '17 at 11:56

0 Answers0