Reputation: 419
I'm using slim framework v4 for building API. I discovered that using custom headers doesn't work at all. I will appreciate any lead on resolving this issue.
I have followed the documentation on https://www.slimframework.com/docs/v4/cookbook/enable-cors.html and this is not able to resolve the issue.
I set some config on Apache
Header always set Access-Control-Allow-Origin "*" Header always set Access-Control-Allow-Headers "Custom-Token"
<script>
axios({
method: 'get',
url: 'http://localhost:8080/income/',
headers: {
'Content-Type': 'application/json',
'Custom-Token': 'vvvv',
'Access-Control-Allow-Headers': 'Custom-Token'
},
responseType: 'json'
})
.then(function (response) {
console.log(response);
}).catch(error => console.log(error));
</script>
The above is originating from domain a and want to get resources from domain b
I got Access to XMLHttpRequest at 'http://localhost:8080/income/' from origin 'http://localhost:8020' has been blocked by CORS policy: Request header field custom-token is not allowed by Access-Control-Allow-Headers in preflight response.
Upvotes: 1
Views: 679
Reputation: 419
I got this fixed by setting the custom header from the PHP side
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Custom-Token');
And more importantly, echoing a text before the preflight response
$app->options('/{routes:.*}', function (Request $request, Response $response) {
// CORS Pre-Flight OPTIONS Request Handler
echo "OK!";
return $response;
});
Upvotes: 1