Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 907
spice Avatar asked Oct 29 '18 04:10

spice


2 Answers

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

like image 102
Iker Avatar answered Sep 17 '22 21:09

Iker


FYI, the previous solution didn't solve the problem for me. I have MAMP PRO 6.0.1.

I solved it by adding

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"

To the Additional parameters for directive:

MAMP Pro Apache configuration

like image 20
Minor Solis Avatar answered Sep 21 '22 21:09

Minor Solis