Laravel 5.1 API Enable Cors

2022-08-30 10:48:04

我专门寻找一些在laravel 5.1上启用cors的方法,我发现了一些库,例如:

https://github.com/neomerx/cors-illuminate

https://github.com/barryvdh/laravel-cors

但是他们都没有专门针对Laravel 5.1的实现教程,我试图配置但它不起作用。

如果有人已经在laravel 5.1上实现了CORS,我将不胜感激...


答案 1

这是我的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)
    {

        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

要使用 CORS 中间件,您必须首先在 app\Http\Kernel.php 文件中注册它,如下所示:

protected $routeMiddleware = [
        //other middlewares
        'cors' => 'App\Http\Middleware\CORS',
    ];

然后,您可以在路线中使用它

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
编辑:在Laravel ^ 8.0中,您必须导入控制器的命名空间并使用如下类:
use App\Http\Controllers\ExampleController;

Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');

答案 2

我总是使用一个简单的方法。只需将以下行添加到文件中即可。我认为您不必使用中间件。\public\index.php

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

推荐