Search code examples
.htaccesscorsmamp-pro

CORS will not enable with MAMP localhost


I've built a RESTful Api in PHP on a local machine and everything is working perfectly. Preflight requests are sending the correct responses etc, everything handled by PHP is working like a dream.

But if I try to access an image in a public folder (programatically via javascript in this instance) I'm getting the infuriating :

Access to XMLHttpRequest at 'http://localhost/tmp/avatars/user.jpg' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've set the following in the .htaccess file in the public root dir, and in the MAMP Apache <Directory> and <VirtualHost> directives but it is just refusing to work.

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

CORS is a pain in the arse at the best of times, but this is just ridiculous. Why isn't this working?

Any ideas?


Solution

  • Change the httpd.conf file from apache folder in MAMP and add the following code on the Directory tag (line204-208).

    <Directory />
        Options Indexes FollowSymLinks
        AllowOverride All
        Header set Access-Control-Allow-Origin "*"  
    </Directory>
    

    You can open with nano and modify it.

    #nano /Applications/MAMP/conf/apache/httpd.conf
    

    Then restart your MAMP server and should be working properly.

    I solved the same issue like that.

    Also you can solve it using a Google Chrome Extension called "Allow CORS: Access-Control-Allow-Origin".

    But be aware that this will only work with your Chrome Browser. The most efficient solution is the first one, modifying the configuration file on the server.

    Good luck