错误CORS Laravel-访问控制允许来源

时间:2020-05-01 22:29:48

标签: angular laravel cors

我已经使用Angular开发了其余的Laravel API。

  • Laravel:-> 5.7 *
  • 角度:-> 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

1st-创建一个子域

  1. 我将Laravel项目上传到了文件夹
  2. 在IONOS中创建一个子域
  3. 创建指向Laravel公用文件夹的子域
  4. 修改Angular的全局变量以匹配子域。

第二个-中间件

//我们创建了一个中间件

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

第三-水果蛋糕

安装

composer require fruitcake / laravel-cors

然后进行所有设置

链接:https://github.com/fruitcake/laravel-cors


实际状态

中间件

<?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 ---配置

    '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 :(得分:-3)

通常,您必须设置服务器以接受Corss。 尝试以这种方式编辑您的aache配置(在您的httpd.conf或.htaccess文件中)

标头设置了Access-Control-Allow-Origin“ *”

为确保您的配置正确,请使用

apachectl -t

然后重新启动apache