0

I have an Api rest made with Laravel protected with JWT. The login works correctly, however, when using the Bearer Token returned by the login I get the error:

Access to XMLHttpRequest at 'http: //api-laravel3.test/api/movies' from origin 'http: // localhost: 8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Postman access via Bearer Token works correctly. The problem occurs with Axios

     var token = localStorage.getItem('user-token');

      axios.get('http://api-laravel3.test/api/movies', { 
        headers:{
          'Content-Type': 'application/json',
          'Authorization': 'Bearer '+token,
        }
      }).then(function (response) {
        console.log('OK ' + response.status);
        return response.data
      })
      .catch(function (error) {
          console.log('Error: ' + error.response );
          //return Promise.reject(error);
      });

1 Answers1

0

I believe, you can solve your problem by adding those lines on your /public/index.php. But it is not elegant if you mind.

header('Access-Control-Allow-Origin: *');  
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");

For better solution, you can create a new middleware for your Laravel application. You should look at this answer to learn more: https://stackoverflow.com/a/44683779/4448438

9uru
  • 1
  • 1
  • 1