Laravel 5.1 API 启用 Cors [英] Laravel 5.1 API Enable Cors

查看:43
本文介绍了Laravel 5.1 API 启用 Cors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 的实现教程,我尝试配置但它不起作用.

but none of them has a implementation tutorial specifically to Laravel 5.1, I tried to config but It doesn't work.

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

If someone already implemented CORS on laravel 5.1 I would be grateful for the help...

推荐答案

这是我的 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 文件中注册它,如下所示:

To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:

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

然后你可以在你的路由中使用它

Then you can use it in your routes

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');

这篇关于Laravel 5.1 API 启用 Cors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆