gpt4 book ai didi

php - Laravel 5.1 API 启用 Cors

转载 作者:IT王子 更新时间:2023-10-28 23:44:23 26 4
gpt4 key购买 nike

我已经寻找了一些在 laravel 5.1 上启用 cors 的方法,我发现了一些类似的库:

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

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

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

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

最佳答案

这是我的 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 使用它

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

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

关于php - Laravel 5.1 API 启用 Cors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33076705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com