I was developing an Ionic Hybrid App that fetches results from the drupal 8 websites and shows recent news with categories. That app also has some basic features like login, signup, bookmarking articles, and commenting. Drupal 8 has built-in modules for REST Web Services which expose entities and other resources using REST API endpoints. I also build some custom REST resources to send responses my way. In-app, I have implemented some providers which send ajax requests to endpoints with HTTP Basic Authentication and get JSON responses, this I display results in-app. It’s a simple app but during the development phase, I got CORS error when app ajax hit the REST endpoint. After some research, I have found a solution that works for me.
How to set CORS headers in drupal 8?
You can set the CORS header in either way listed below.
1:- Setting CORS in services.yml
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: ['POST', 'GET', 'OPTIONS', 'PATCH', 'DELETE']
# 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: true
Make sure you put only those headers that you required (Avoid extra) or enable only that configuration that you required for security purposes.
2:- Send header from your custom REST plugin resource with the response.
<?php
/**
* function can be get, post, patch, delete
**/
function post($lang) {
// Authentication logic here
// logic of your REST Resource here.
// Resource response
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PATCH, DELETE',
'Access-Control-Allow-Headers' => 'Authorization'
];
$response = new ResourceResponse($response_result, $response_code, $headers);
// Configure caching for results
if ($response instanceof CacheableResponseInterface) {
$response->addCacheableDependency(new ArticleCachableDepenency(count($response_result),$entities));
}
return $response;
}
This function is extracted from my custom rest resource plugin.
3:- Using Event Subscriber.
Method is the same as I do in the REST Resource plugin but uses event subscribers.
I will add an article about how to make an event subscriber.