1.新建中间件Cors.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
*
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
//Intercepts OPTIONS requests
if ($request->isMethod('OPTIONS')) {
$response = response('', 200);
} else {
// Pass the request to the next middleware
$response = $next($request);
}
// Adds headers to the response
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Credentials', 'true');
$response->header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-token");
$response->header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
// Sends it
return $response;
}
}
2.注册中间件,修改bootstrap/app.php
$app->middleware([
'cors' => App\Http\Middleware\Cors::class,
]);
网友评论