I have trouble making an XHR request with axios from a Vue app to a PHP API running on WAMP.
The error message is the following :
Access to XMLHttpRequest at ‘http://localhost/myapp/api/test/1‘ from origin ‘http://localhost:8080‘ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
As you can see, it’s a problem with CORS. After some documentation, here is what I have been doing to fix it (still not working).
Axios call :
axios({
method: 'get',
url: 'http://localhost/myapp/api/test/1',
data: JSON.stringify({}),
headers: { 'Content-Type': 'application/json', },
crossdomain: true,
});
If I visit http://localhost/myapp/api/test/1 in my web browser, I got my response.
I attempted putting this line of code in my PHP API, in my entry point (index.php)
header('Access-Control-Allow-Origin: *');
I configured WAMP :
Changed httpd-vhosts.conf and httpd.conf
# Virtual Hosts
<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
Header set Access-Control-Allow-Origin "*"
AllowOverride All
Require local
</Directory>
</VirtualHost>
-
Activated the “headers_module” in apache’s modules
-
Rebooted everything, cleared my cache, tried from another browser …
Still not working, am I missing something ?
2
Answers
I use this at the top of my index.php file to fix CORS problems:
Try this extension for cross origin.
https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc