Allow-Acces CORS

I want to let my frontend page fetch data from backend and I have to deal with CORS.
My frontend page is

In backend I have made .htaccess file with content:

Header set Access-Control-Allow-Origin

And it doesn’t work. What would be a correct content of .htaccess?


Does your apache installation have the mod_headers enabled? Although not required, did you try to reload the server (if you can, of course)?

I’m not sure if I understand correctly. My backend is not on localhost, but it is in hosting somewhere in the internet.

Do you know what software is your hosting using? Create a PHP file with this: <?php phpinfo(); ?>, then load that page. There you have all the information about the server and the PHP installation.

Are you sure you cannot contact the back end? Try using postman (or any other similar tool) to contact it, and if it fails, then there’s another problem, not only the headers.

1 Like

in some cases even if when you Allow CORS headers on htaccess file of apache server, you would need to allow the headers on back-end code as well.

A little background about what’s happening: it seems like your front-end code is built and runs on an apache server. Your back-end code could also have been built and loaded on an apache server. But the problem is they don’t know each other so when your front-end code calls an api browser throws CORS.

As @skaparate suggested you need first see if you can hit your back-end code (API). I agree that postman is the best option. When using Postman you don’t have to worry about CORS.

After you were able to hit your API correctly, and you’re sure that the api url’s you’re using in postman are the same your front-end code uses then it’s time to see if back-end code needs to have CORS specific headers.

If you checked everything else and you’re still getting CORS issue AND you’re having access to your back-end code, then it’s time to add CORS headers to your back-end code depending on the language you’re using.
I know for .Net and Java there are great articles out there guiding you on how to set this up step by step.

If you were still facing the issue, just let us know and we’ll solve it together :call_me_hand:

1 Like

To be precise:
Using Access-Control-Allow-Origin “*” - it works, but I want to allow only my frontend website to access it.

Hehehe, you should have started with this.

When you set your domain as the allowed origin, does your front end reach the back end? Does it display any errors on either side? Do you have access to the error and access logs on the server?

I don’t have enough information to help :stuck_out_tongue:. Maybe @shervinee knows something I don’t :grin:.

1 Like

Ah okay then so in that case if you replace the * with the app url it should work fine. something like below.
Access-Control-Allow-Origin: https://foo.example