Sudar
Sudar

Reputation: 20000

Enable and configure cors in Drupal

I am debugging a Drupal issue where it is used as a headless api server.

I have to make a POST request to Drupal's contact form REST Endpoint when someone submits a form in a JavaScript app.

The API works when I test it from a REST Client.

But when I run the same code from JavaScript in a browser, I am getting a cors issue.

I have made sure cors is enabled in the sites/default/default.services.yml file.

But the changes are not taking effect.

The following are the relevant contents of the sites/default/default.services.yml file

  cors.config:
    enabled: true
    # Specify allowed headers, like 'x-allowed-header'.
    allowedHeaders: ['*']
    # Specify allowed request methods, specify ['*'] to allow all possible ones.
    allowedMethods: ['*']
    # Configure requests allowed from specific origins.
    allowedOrigins: ['*']
    # Sets the Access-Control-Expose-Headers header.
    exposedHeaders: true
    # Sets the Access-Control-Max-Age header.
    maxAge: false
    # Sets the Access-Control-Allow-Credentials header.
    supportsCredentials: false

I am getting following error in browser.

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

I tried to change the sites/default/default.services.yml to the following, but I am still getting the same problem.

allowedHeaders: ['x-csrf-token', 'authorization', 'content-type', 'accept', 'origin', 'x-requested-with']

Upvotes: 1

Views: 3400

Answers (2)

Sudar
Sudar

Reputation: 20000

Thanks to everyone for the input.

It looks like the reason why it was not working was because the Drupal installation already had the old 'Drupal Cors' module also enabled which was taking precedence.

Once I disabled it, the changes that I made to the services.yml started to work.

Upvotes: 3

2pha
2pha

Reputation: 10165

Change the file name from default.services.yml to services.yml.
Also, the exposedHeaders property should be an array of header names, or false, but never 'true'.
src: https://www.drupal.org/node/2715637

Upvotes: 4

Related Questions