我寻找了一些在 Laravel 5.1 上启用CORS的方法,例如:
https://github.com/neomerx/cors-illuminate
https://github.com/barryvdh/laravel-cors
但是,它们都没有专门针对 Laravel 5.1 的实现教程。虽然我尝试进行配置,但仍无法正常工作。
如果有人已经在 Laravel 5.1 上实现了CORS,我将不胜感激地接受帮助...
我寻找了一些在 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::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
use App\Http\Controllers\ExampleController;
Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');
protected $middleware
数组内添加\App\Http\Middleware\Cors::class
。如果有人和我一样遇到困难,可以尝试这个方法。 - arikanmstf我总是使用一种简单的方法。只需将以下行添加到\public\index.php
文件中即可。 我认为你不必使用中间件。
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
index.php
文件在所有HTTP请求中都被使用,这是一种简单且用户友好的方式。 - Joel JamesPUT
和 DELETE
),这些请求将在一个 OPTIONS
请求之前进行,如果在 $routeMiddleware
数组中指定中间件(并在路由定义文件中使用该中间件),则无法工作,除非您还为 OPTIONS
定义了一个路由处理程序。这是因为没有 OPTIONS
路由,Laravel 将会在没有 CORS 标头的情况下内部响应该方法。$middleware
数组中定义全局运行的中间件,要么在 $middlewareGroups
或 $routeMiddleware
中进行定义,并同时为 OPTIONS
定义一个路由处理程序。可以像这样实现:Route::match(['options', 'put'], '/route', function () {
// This will work with the middleware shown in the accepted answer
})->middleware('cors');
我也为相同目的编写了一个中间件,看起来类似,但体积更大,因为它试图更加可配置并处理一堆条件:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
private static $allowedOriginsWhitelist = [
'http://localhost:8000'
];
// All the headers must be a string
private static $allowedOrigin = '*';
private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';
private static $allowCredentials = 'true';
private static $allowedHeaders = '';
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (! $this->isCorsRequest($request))
{
return $next($request);
}
static::$allowedOrigin = $this->resolveAllowedOrigin($request);
static::$allowedHeaders = $this->resolveAllowedHeaders($request);
$headers = [
'Access-Control-Allow-Origin' => static::$allowedOrigin,
'Access-Control-Allow-Methods' => static::$allowedMethods,
'Access-Control-Allow-Headers' => static::$allowedHeaders,
'Access-Control-Allow-Credentials' => static::$allowCredentials,
];
// For preflighted requests
if ($request->getMethod() === 'OPTIONS')
{
return response('', 200)->withHeaders($headers);
}
$response = $next($request)->withHeaders($headers);
return $response;
}
/**
* Incoming request is a CORS request if the Origin
* header is set and Origin !== Host
*
* @param \Illuminate\Http\Request $request
*/
private function isCorsRequest($request)
{
$requestHasOrigin = $request->headers->has('Origin');
if ($requestHasOrigin)
{
$origin = $request->headers->get('Origin');
$host = $request->getSchemeAndHttpHost();
if ($origin !== $host)
{
return true;
}
}
return false;
}
/**
* Dynamic resolution of allowed origin since we can't
* pass multiple domains to the header. The appropriate
* domain is set in the Access-Control-Allow-Origin header
* only if it is present in the whitelist.
*
* @param \Illuminate\Http\Request $request
*/
private function resolveAllowedOrigin($request)
{
$allowedOrigin = static::$allowedOrigin;
// If origin is in our $allowedOriginsWhitelist
// then we send that in Access-Control-Allow-Origin
$origin = $request->headers->get('Origin');
if (in_array($origin, static::$allowedOriginsWhitelist))
{
$allowedOrigin = $origin;
}
return $allowedOrigin;
}
/**
* Take the incoming client request headers
* and return. Will be used to pass in Access-Control-Allow-Headers
*
* @param \Illuminate\Http\Request $request
*/
private function resolveAllowedHeaders($request)
{
$allowedHeaders = $request->headers->get('Access-Control-Request-Headers');
return $allowedHeaders;
}
}
我也写了一篇关于这个的博客文章。
对于我来说,我把这些代码放在public\index.php
文件中。对于所有的CRUD操作,它都能正常工作。
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");
barryvdh/laravel-cors 只需要在几个关键点上启用即可与 Laravel 5.1 完美配合。
将其添加为 composer 依赖项后,确保您已发布了 CORS 配置文件,并根据需要调整 CORS 标头。以下是我在 app/config/cors.php 中的设置:
<?php
return [
'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE'],
'exposedHeaders' => ['DAV', 'content-length', 'Allow'],
'maxAge' => 86400,
'hosts' => [],
];
接下来,还有一个在文档中没有提到的步骤,你需要在应用内核中添加CORS处理程序'Barryvdh\Cors\HandleCors'
。我喜欢将它放在全局中间件堆栈中使用。就像这样:
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'Barryvdh\Cors\HandleCors',
];
但是你可以将它用作路由中间件并放置在特定的路由上。
这应该使该包与L5.1兼容。
Laravel 8
创建一个中间件
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CorsMiddleware
{
public function handle(Request $request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', config('cors.allowed_origins'))
->header('Access-Control-Allow-Methods', config('cors.allowed_methods'))
->header('Access-Control-Allow-Headers',config('cors.allowed_headers'));
}
}
config/cors.php
return [
'paths' => [
'api/*',
'admin/api/*',
'sanctum/csrf-cookie'
],
'allowed_methods' => [ //'GET, POST, PUT, PATCH, DELETE, OPTIONS'
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS'
],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => [// 'Content-Type, Authorization, Accept'
'Content-Type',
'Authorization',
'Accept'
],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
kernel.php for http
protected $middleware = [
... ,
\App\Http\Middleware\CorsMiddleware::class, // Cors middlewate
];
控制器操作
Route::post('login','AuthController@login');
class AuthController extends Controller {
...
public function login() {
dd(['key' => 'value']);
//OR
die(['key' => 'value']);
//OR
print_r(['key' => 'value');
exit();
}
...
}
控制器操作
Route::post('login','AuthController@login');
class AuthController extends Controller {
...
public function login() {
return response()->json(['key' => 'value'], 200);
// OR
return ['key' => 'value'];
// OR
$data = ['key' => 'value'];
return $data;
}
...
}
Chrome浏览器 -> 开发者工具 -> 网络选项卡
如果有任何问题,那么您的响应头将不会显示在此处。
https://github.com/fruitcake/laravel-cors
请使用这个库。按照此存储库中提到的说明操作。 dd() 或 die() ,因为这个库将无法工作。始终使用带有CORS URL的返回。
谢谢
只需将其用作中间件即可
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Methods', '*');
return $response;
}
}
并在您的内核文件中注册中间件,路径为app/Http/Kernel.php
,选择您喜欢的组,一切都会很好。