Laravel вызов API из Vue. js вызывает CORS для маршрутов GET - PullRequest
0 голосов
/ 10 апреля 2020

Недавно я хотел интегрировать интерфейсное приложение VueJS в мое приложение Laravel. Прежде всего, я установил библиотеку fruitcake/laravel-cors в Laravel и установил соединение от Vue.js до Laravel, используя Vue Axios. Теперь работают все типы запросов (POST, PUT, UPDATE ...), кроме 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 Приложение:

  • Топор ios метод получения:

    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

Ответы [ 2 ]

0 голосов
/ 10 апреля 2020

Проблема заключалась в том, что конечный sla sh был сгенерирован следующей функцией:

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

Если slug не передается, то данные запроса функции через API с конечным sla * sh, поэтому убрал параметр slug из вызова функций и API, и проблема решена.

get(resource) {
  return Vue.axios.get(`${resource}`).catch(error => {
    // console.log(error);
    throw new Error(`ApiService ${error}`);
  });
},
0 голосов
/ 10 апреля 2020

Попробуйте с обновлением в этой строке

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

Или также попробуйте очистить кеш, значение конфигурации. и перезапустите сервер и приложение.

...