CORS Error: What is the correct way to configure Symfony 5 to accept CORS?
After struggling with nelmio for a while, I found it easier to go with this ghetto solution:
public/index.php
:
if ($_SERVER['APP_DEBUG']) {
header('Access-Control-Allow-Origin:'.rtrim($_SERVER['HTTP_REFERER'], '/'));
} else {
header('Access-Control-Allow-Origin:yourdomain');
}
header('Access-Control-Allow-Headers:*');
header('Access-Control-Allow-Credentials:true');
header('Access-Control-Allow-Headers:X-Requested-With, Content-Type, withCredentials');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
die();
}
I use this just after the bootEnv
line. I'm using symfony 5+
Hi could you try changing the path from '^/' to '^/api/' in NelmioCorsBundle and add this configuration like this example:
nelmio_cors:
defaults:
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['Content-Type', 'Authorization']
expose_headers: ['Link']
max_age: 3600
paths:
'^/api/':
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_headers: ['X-Custom-Auth', 'Content-Type', 'Authorization', 'Location']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTION']
expose_headers: ['Link', 'Location']
max_age: 3600