skip to Main Content

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


  1. I use this at the top of my index.php file to fix CORS problems:

    function cors() {
        // Allow from any origin
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: *");
            header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
            header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }
    
        // Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                // may also be using PUT, PATCH, HEAD etc
                header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept");
    
            exit(0);
        }
    }
    cors();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search