来自 Vue.js 的 Laravel API 调用导致 GET 路由的 CORS [英] Laravel API call from Vue.js cause CORS for GET routes

查看:24
本文介绍了来自 Vue.js 的 Laravel API 调用导致 GET 路由的 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 应用:

Laravel App:

  • 中间件:

  • Middleware:

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

  • CORS 配置文件:

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

  • ENV file

    API_ALLOWED_ORIGINS=http://localhost:8080
    

  • 路线:

  • Route:

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

  • Vue.JS 应用:

    • axios 获取方法:

    • Axios get method:

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

  • API 调用

  • API Call

    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.

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

    更新

    开发者控制台网络标签:

    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
    

    推荐答案

    问题是由以下函数生成的尾部斜杠:

    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}`);
      });
    },
    

    当没有传递slug时,函数通过带有尾部斜杠的API请求数据,因此从函数和API调用中删除了slug参数,问题解决.

    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}`);
      });
    },
    

    这篇关于来自 Vue.js 的 Laravel API 调用导致 GET 路由的 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆