Ошибка CORS Laravel - Access-Control-Allow-Origin - PullRequest
0 голосов
/ 02 мая 2020

Я разработал API отдыха Laravel с Angular.

  • Laravel: -> 5.7 *
  • Angular: -> 8.2.9
  • __________ Angular CLI: 8.3.8

Проект разделен на 2 папки, каждая из которых имеет свою технологию.

После завершения проекта переместите его в производство с сервером IONOS.

Но я получил эту ошибку:

Access to XMLHttpRequest at 'https://api.alfarim.es/category' from origin 'http://www.alfarim.es' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
app.component.ts:63 

HttpErrorResponse

api.alfarim.es/category:1 Failed to load resource: net::ERR_FAILED

1-й - Создать поддомен

  1. Я загрузил проект Laravel в папка
  2. Создание субдомена в IONOS
  3. Создание субдомена, указывающего на папку Laravel publi c
  4. Изменение глобальной переменной Angular для соответствия Субдомен.

2-й - Промежуточное программное обеспечение

// Создаем промежуточное программное обеспечение

->header('Access-Control-Allow-Origin', '*’)
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS’);

// Входим в ядро ​​

'cors' => \App\Http\Middleware\Cors::class,

// Добавить к маршрутам

Route::group(['middleware' => 'cors'], function(){
    //rutes
});

И затем выполнить все настройки

Ссылка: https://github.com/fruitcake/laravel-cors

3-й - Fruitcake

Установка

composer require fruitcake / laravel-cors

А потом все делать Tings

Ссылка: https://github.com/fruitcake/laravel-cors


Фактическое состояние

Middleware

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
        ->header('Access-Control-Allow-Origin', '*’)
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS’);

    }
}

Ядро

protected $middleware = [
      ....
      \Fruitcake\Cors\HandleCors::class, 
    ];

protected $routeMiddleware = [
        .....
        'cors' => \App\Http\Middleware\Cors::class,
    ];

cors. php --- config

    'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    '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,

    $app->configure('cors');
];

Маршруты

Route::group(['middleware' => 'cors'], function(){
    //.....
    Route::post('/api/register/','UserController@register');
    }); 

1 Ответ

0 голосов
/ 02 мая 2020

Обычно вы должны настроить свой сервер для принятия Corss. попробуйте отредактировать конфигурацию aache (в файле httpd.conf или в файле .htaccess) следующим образом:

Установить заголовок Access-Control-Allow-Origin "*"

, чтобы убедиться, что правильная конфигурация, используйте

apachectl -t

и затем перезапустите apache

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...