1

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.

Olotin Temitope
  • 419
  • 6
  • 13
  • If you can post what you have tried so far and any errors that you are facing, it will be helpful for others to help you. – Dula Oct 27 '21 at 10:33

1 Answers1

1

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;
    });
Olotin Temitope
  • 419
  • 6
  • 13
  • Well done solving this by yourself. This is the sole way to understand CORS. Note that `localhost` is adding to the confusion. – NVRM Oct 27 '21 at 11:56
  • @NVRM. I'm just testing it using 2 different ports on localhost. Thanks, I will try it on a live domain and verify if this changes. – Olotin Temitope Oct 27 '21 at 12:40
  • 1
    Now it's okay, for the culture, between around Firefox v60 and v80 (not long ago..), the localhost was blocked by CORS. Then it was allowed, mostly for permissions issues, webcam, GPS etc, nothing was working! – NVRM Oct 27 '21 at 13:19