一尘不染

Laravel 5.1 API启用Cors

php

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

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

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

但是他们都没有专门针对Laravel 5.1的实现教程,我尝试进行配置,但没有用。

如果有人已经在laravel 5.1上实现了CORS,我将非常感谢您的帮助…


阅读 306

收藏
2020-05-26

共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'));
2020-05-26