【问题标题】:Laravel API call from Vue.js cause CORS for GET routes来自 Vue.js 的 Laravel API 调用导致 GET 路由的 CORS
【发布时间】:2020-07-23 10:33:24
【问题描述】:

我最近想将 VueJS 前端应用程序集成到我的 Laravel 应用程序中。首先,我在Laravel 中安装了fruitcake/laravel-cors 库,并使用Vue Axios 建立了从Vue.js 到Laravel 的连接。现在所有类型的请求都可以正常工作(POSTPUTUPDATE...),GET 除外。规格如下:

Laravel 应用:

  • 中间件:

    protected $middleware = [
       //... Rest of the middleware
       //CORS middleware
       \Fruitcake\Cors\HandleCors::class 
    ];
    
  • CORS 配置文件:

    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 文件

    API_ALLOWED_ORIGINS=http://localhost:8080
    
  • 路线:

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

Vue.JS 应用程序:

  • axios 获取方法:

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

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

浏览器输出:

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.

POST 相同的路由正在工作,但现在与GET 一起工作。

更新

开发者控制台网络标签:

    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

【问题讨论】:

    标签: laravel api vue.js axios


    【解决方案1】:

    问题在于以下函数生成的斜杠:

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

    slug没有传递时,函数通过API请求数据,尾部斜杠,所以从函数和API调用中去掉slug参数,问题就解决了。

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

    【讨论】:

      【解决方案2】:

      尝试更新这一行

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

      或者也尝试清除缓存,配置值。并重新启动服务器和应用程序。

      【讨论】:

      • 以上操作没有结果。我发布了自己的答案。
      猜你喜欢
      • 1970-01-01
      • 2021-09-18
      • 2016-06-15
      • 1970-01-01
      • 2020-10-17
      • 2019-02-19
      • 2019-03-06
      • 1970-01-01
      • 2016-08-28
      相关资源
      最近更新 更多