1

I have a ReactJS app that fetches an external API URL with the following structure.

fetch(url) // or fetch(url, {mode:'cors'})
  .then(response => response.json())
  .then(data => {

In my browser, when it tries to render the component, I am getting the following error message

Failed to load https://XXXXX/jsondata: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So I research how to enable CORS in Drupal 8 and doing trial and error for different configurations didn't work.

This is my current cors.config under services.yml file

  cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with', 'access-control-allow-origin','x-allowed-header','*']
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: ['*'] // or ['POST', 'GET', 'OPTIONS', 'DELETE', 'PUT', 'PATCH']
    # Configure requests allowed from specific origins.
    allowedOrigins: ['https://XXXX/','*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: true // or false
    # Sets the Access-Control-Max-Age header.
    maxAge: false // or 1000
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: true // or false

I have tried to install a Chrome extension that is amazing that removes this error but of course this will only be working in my device.

Im not entirely sure but is this something to change Drupal CORS config or allowing Access-Control-Allow-Origin on the API URL side (https://XXXX)?

  • I strongly advise against using * in any setting. Also check that you edited the right file. This only works if someone is making a request against your Drupal app, but doesn’t apply if you have code talking to another site/server. – Kevin Jun 25 '18 at 12:07
  • yes, thanks for your advice. And you are right, in my case, its Drupal trying to access another site. So what should be properly done is to have the other site configured to allow Access-Control-Allow-Origin, right? – John Rey Tanquinco Jun 26 '18 at 0:53
1

I would just like to answer my own question. After reading more documentation about how CORS works, I found out that, to allow Drupal access other site/server, CORS must be enabled in the other party not in Drupal site itself. Some basic explanation found here too. https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work/10636765#10636765

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.