Laravel 5.1 API 启用Cors
Laravel 5.1 API Enable Cors
我一直在寻找一些在 laravel 5.1 上启用 cors 的方法,具体来说,我找到了一些库,例如:
https://github.com/neomerx/cors-illuminate
https://github.com/barryvdh/laravel-cors
但是其中 none 有专门针对 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'));
编辑:在 Laravel ^8.0 中,您必须导入控制器的命名空间并像这样使用 class:
use App\Http\Controllers\ExampleController;
Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');
我总是使用简单的方法。只需将以下行添加到 \public\index.php
文件。我认为你不必使用中间件。
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
barryvdh/laravel-cors 与 Laravel 5.1 完美配合,只需几个关键点即可启用它。
将其添加为作曲家依赖项后,请确保您已发布 CORS 配置文件并根据需要调整 CORS headers。这是我在 app/config/cors.php
中的样子
<?php
return [
'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE'],
'exposedHeaders' => ['DAV', 'content-length', 'Allow'],
'maxAge' => 86400,
'hosts' => [],
];
在此之后,还有一个文档中没有提到的步骤,您必须在 App 内核中添加 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 5.4 不幸的是,虽然接受的答案看起来不错,但对于预检请求(如 PUT
和 DELETE
),其前面会有一个 OPTIONS
请求,在 $routeMiddleware
数组中指定中间件(并在路由定义文件中使用它)将不起作用,除非您也为 OPTIONS
定义路由处理程序。这是因为没有 OPTIONS
路由 Laravel 将 internally respond 到没有 CORS headers.
的那个方法
所以简而言之,要么在 $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;
}
}
在这上面也写了一个blog post
只用这个作为中间件
<?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
您喜欢哪个组,一切都会好起来的
对我来说,我将这些代码放在 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");
如果您不return通过函数闭包或通过控制器操作从您的路由中获得响应,那么它将无法工作。
没用
控制器操作
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;
}
...
}
测试 CORS
Chrome -> 开发者工具 -> 网络选项卡
如果出现任何问题,您的回复 headers 将不会出现在这里。
https://github.com/fruitcake/laravel-cors
使用这个库。按照此 repo 中提到的说明进行操作。
切记不要在 CORS URL 中使用 dd()
或 die()
,因为该库将不起作用。始终将 return 与 CORS URL.
一起使用
谢谢
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 对于 http
protected $middleware = [
... ,
\App\Http\Middleware\CorsMiddleware::class, // Cors middlewate
];
我一直在寻找一些在 laravel 5.1 上启用 cors 的方法,具体来说,我找到了一些库,例如:
https://github.com/neomerx/cors-illuminate
https://github.com/barryvdh/laravel-cors
但是其中 none 有专门针对 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'));
编辑:在 Laravel ^8.0 中,您必须导入控制器的命名空间并像这样使用 class:
use App\Http\Controllers\ExampleController;
Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');
我总是使用简单的方法。只需将以下行添加到 \public\index.php
文件。我认为你不必使用中间件。
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
barryvdh/laravel-cors 与 Laravel 5.1 完美配合,只需几个关键点即可启用它。
将其添加为作曲家依赖项后,请确保您已发布 CORS 配置文件并根据需要调整 CORS headers。这是我在 app/config/cors.php
中的样子<?php return [ 'supportsCredentials' => true, 'allowedOrigins' => ['*'], 'allowedHeaders' => ['*'], 'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE'], 'exposedHeaders' => ['DAV', 'content-length', 'Allow'], 'maxAge' => 86400, 'hosts' => [], ];
在此之后,还有一个文档中没有提到的步骤,您必须在 App 内核中添加 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 5.4 不幸的是,虽然接受的答案看起来不错,但对于预检请求(如 PUT
和 DELETE
),其前面会有一个 OPTIONS
请求,在 $routeMiddleware
数组中指定中间件(并在路由定义文件中使用它)将不起作用,除非您也为 OPTIONS
定义路由处理程序。这是因为没有 OPTIONS
路由 Laravel 将 internally respond 到没有 CORS headers.
所以简而言之,要么在 $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;
}
}
在这上面也写了一个blog post
只用这个作为中间件
<?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
您喜欢哪个组,一切都会好起来的
对我来说,我将这些代码放在 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");
如果您不return通过函数闭包或通过控制器操作从您的路由中获得响应,那么它将无法工作。
没用
控制器操作
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;
}
...
}
测试 CORS
Chrome -> 开发者工具 -> 网络选项卡
如果出现任何问题,您的回复 headers 将不会出现在这里。
https://github.com/fruitcake/laravel-cors
使用这个库。按照此 repo 中提到的说明进行操作。
切记不要在 CORS URL 中使用 dd()
或 die()
,因为该库将不起作用。始终将 return 与 CORS URL.
谢谢
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 对于 http
protected $middleware = [
... ,
\App\Http\Middleware\CorsMiddleware::class, // Cors middlewate
];