skip to Main Content

I have developed application in Angular 7 and APIs in Laravel 5.7.

For CORS issue, I have also installed barryvdh/laravel-cors package in Laravel and its working fine on local.

But when I deployed these both applications on Godaddy single hosting, that is Starter Linux Hosting with cPanel

  1. Angular app in main directory public_html
  2. Laravel APIs in public_html/api directory which points to
    public_html/api/public

APIs are not working and I am seeing this error

Access to XMLHttpRequest at 'http://api.example.com/api/documentations?page=1' from origin 'http://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request

I have seen lot of answers on stackoverflow and on other sources, nothing seems to be working for me.

I tried adding headers to .htaccess file

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

As well as directly to index.php but with no luck.

header('Access-Control-Allow-Origin', '*')

Any idea or help is highly appreciated. Thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    Thank you @ceejayoz for your valuable comments and answer. I am able to find the issue

    I am having two .htaccess files. For main domain, one at

    public_html/.htaccess
    

    and another for subdomain at

    public_html/api/public/.htaccess
    

    The one at public_html/.htaccess having this line to protect the files inside the public_html/api directory from root access of main domain

    RedirectMatch 403 ^/api/.*$
    

    When I commented/removed this line, APIs started working but files inside public_html/api directory were not secure.

    Then to secure the files, I created one more file at public_html/api/.htaccess and added these lines

    RewriteEngine On
    RewriteRule !^public/ - [F,NC]
    

    And I achieved both: APIs are working and files inside public_html/api are secured.


  2. Redirect is not allowed for a preflight request

    Since you have a HTTP to HTTPS redirect in place, and your API calls are trying to access http://api.example.com/api/documentations?page=1, they’re going to fail, because (as the message states) you can’t redirect a CORS preflight.

    Update your code to make the API calls over HTTPS.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search