Laravel API call from Vue.js cause CORS for GET routes

别等时光非礼了梦想. 提交于 2020-08-09 13:45:29

问题


I recently wanted to integrate the VueJS front end app to my Laravel application. First of all, I installed fruitcake/laravel-cors library in Laravel and made the connection from Vue.js to Laravel using Vue Axios. Now all types of requests working (POST, PUT, UPDATE...) except GET. Specifications are as follow:

Laravel App:

  • Middleware:

    protected $middleware = [
       //... Rest of the middleware
       //CORS middleware
       \Fruitcake\Cors\HandleCors::class 
    ];
    
  • CORS Config file:

    return [
    
        /*
         * You can enable CORS for 1 or multiple paths.
         * Example: ['api/*']
         */
        'paths' => ['api/*'],
    
        /*
        * Matches the request method. `[*]` allows all methods.
        */
        'allowed_methods' => ['POST', 'GET', 'OPTIONS', 'PUT', 'PATCH', 'DELETE'],
    
        /*
         * Matches the request origin. `[*]` allows all origins.
         */
        'allowed_origins' => explode(' ', env('API_ALLOWED_ORIGINS')),
    
        /*
         * Matches the request origin with, similar to `Request::is()`
         */
        'allowed_origins_patterns' => [],
    
        /*
         * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
         */
        'allowed_headers' => ['*'],
    
        /*
         * Sets the Access-Control-Expose-Headers response header with these headers.
         */
        'exposed_headers' => [],
    
        /*
         * Sets the Access-Control-Max-Age response header when > 0.
         */
        'max_age' => 0,
    
        /*
         * Sets the Access-Control-Allow-Credentials header.
         */
        'supports_credentials' => false,
    ];
    
  • ENV file

    API_ALLOWED_ORIGINS=http://localhost:8080
    
  • Route:

    Route::get('/something', 'SomeComtroller@someAction');
    

Vue.JS App:

  • Axios get method:

    get(resource, slug = "") {
        return Vue.axios.get(`${resource}/${slug}`).catch(error => {
          // console.log(error);
          throw new Error(`ApiService ${error}`);
        });
    },
    
  • API Call

    ApiService.get("something")
      .then(({ data }) => {
         console.log(data);
      })
      .catch(({ response }) => {
         console.log(response.data);
       });
    

Browser Output:

Access to XMLHttpRequest at 'http://laravel.app/api/something' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

The same route with POST is working, but now working with GET.

Update

Developer Console Network Tab:

    HTTP/1.1 301 Moved Permanently
    Date: Fri, 10 Apr 2020 16:54:26 GMT
    Server: Apache
    Location: http://laravel.app/api/something
    Content-Length: 244
    Keep-Alive: timeout=5, max=100
    Connection: Keep-Alive
    Content-Type: text/html; charset=iso-8859-1
    X-Pad: avoid browser bug

回答1:


Try with an update on this line

'allowed_origins' => explode(' ', env('API_ALLOWED_ORIGINS', 'http://localhost:8080')),

Or also try with clear the cache, config value. and restart the server and the application.




回答2:


The problem was with trailing slash generated by the following function:

get(resource, slug = "") {
  return Vue.axios.get(`${resource}/${slug}`).catch(error => {
    // console.log(error);
    throw new Error(`ApiService ${error}`);
  });
},

When the slug is not passed then the function request data through API with trailing slash, so removed the slug parameter from function and API call and the problem is solved.

get(resource) {
  return Vue.axios.get(`${resource}`).catch(error => {
    // console.log(error);
    throw new Error(`ApiService ${error}`);
  });
},


来源:https://stackoverflow.com/questions/61144313/laravel-api-call-from-vue-js-cause-cors-for-get-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!