laravel-API解决跨域问题
Access to XMLHttpRequest at 'http://mysite2.test/api/authorizations' from origin 'http://localhost:9529' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
创建中间件
创建app/Http/Middleware/Cors.php,设置响应头信息
<?php
/**
* +--------------------------------------------------------+
* @Created by PhpStorm.
* @Category Cors.php
* @Depiction:
* Author: huangwy
* Date: 2020/12/8 15:17
* +--------------------------------------------------------+
*/
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)
{
// 设置允许访问的域地址
$domains = [
'http://localhost:9527',
'http://localhost:9528',
'http://localhost:9529',
'http://mysite2.test',
'https://mysite3.test',
];
// 判断请求头中是否包含ORIGIN字段
if(isset($request->server()['HTTP_ORIGIN'])){
$origin = $request->server()['HTTP_ORIGIN'];
if (in_array($origin, $domains)) {
//设置响应头信息
header('Access-Control-Allow-Origin: '.$origin);
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
}
}
return $next($request);
}
}
注册路由,增加中间件
protected $middleware中添加
\App\Http\Middleware\Cors::class
protected $routeMiddleware中添加
'cors' => \App\Http\Middleware\Cors::class
'api' => [
'throttle:60,1',
'cors',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],