I've looked for some ways to enable cors on laravel 5.1 specifically, I have found some libs like:

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

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

但是他们都没有专门针对Laravel 5.1的实现教程,我try 过配置,但没有效果.

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

推荐答案

Here is my 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)
    {

        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'));
Edit: In Laravel ^8.0 you have to import the namespace of the controller and use the class like this:
use App\Http\Controllers\ExampleController;

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

Laravel相关问答推荐

使用两个日期之间的范围获取两列之间的记录,同时搜索过滤条件

我在 laravel 中插入多个复选框值.我怎样才能做到这一点?

调用字符串上的成员函数

如何在 Laravel 的外部 js 文件中包含 csrf_token()?

Laravel 在维护模式下显示自定义消息

如何判断用户Electron邮件是否已存在

指令allow_call_time_pass_reference警告

从 Laravel Session 数组中删除项目

如何在 laravel 5.2 中显示 500 内部服务器错误页面?

Laravel 中的 index()" 是什么意思?

Lumen和 MongoDB?

如何使用 Laravel 模型访问数据库视图?

将 hasOne 模型附加到另一个 Laravel/Eloquent 模型而不指定 id

Laravel 随机排序

如何在 Laravel 中使用旧输入重定向?

PHP Laravel:如何获取客户端浏览器/设备?

未找到列:1054 未知列 laravel

Laravel 如何从子域 URL 中删除api前缀

如何在 Eloquent Orm 中实现自引用(parent_id)模型

count() 参数必须是数组或在 laravel 中实现可数的对象