Ad

My "Access-Control-Allow-Origin" Header Is Not Working In My .htaccess?

- 1 answer

While I was trying to get information from the "https://api.steampowered.com" API I was getting the error

Access to XMLHttpRequest at 'https://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=<<MyKEY>>&steamid=<<MySteamID>>' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Then I set the AllowOverride to all in my apache2.confand added the header Header set Access-Control-Allow-Origin "https://api.steampowered.com" to my .htaccess located in /var/www/html. (I also tryed it with Header set Access-Control-Allow-Origin "*") I enabled the a2enmod headers with a2enmod headers after that I restarted my webserver with /etc/init.d/apache2 restart. But it still doesn't work.

My .htaccess:

Header set Access-Control-Allow-Origin "*"

My apache2.conf:

<Directory />
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory>

<Directory /usr/share>
        AllowOverride None
        Require all granted
</Directory>

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride all
        Require all granted
</Directory>

My javascript code:

$(document).ready(function () {
    $.getJSON('https://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=<<MyKEY>>&steamid=<<MySteamID>>', function (data) {
        //My code with the data
    });
});

Maybe I need to put the header elsewhere?

Ad

Answer

You have a webpage, https://example.com/ which includes some JavaScript.

That JavaScript wants to read data from https://api.steampowered.com/.

To do this, https://api.steampowered.com/ needs to give permission to https://example.com.

You have configured https://example.com to grant permission to all websites to read data from it.

You haven't configured https://api.steampowered.com/ to grant permission to anyone. (At least I assume you don't work for Steam).

Ad
source: stackoverflow.com
Ad