开启跨域
app/middleware.php
<?php
// 全局中间件定义文件
return [
// 全局请求缓存
// \think\middleware\CheckRequestCache::class,
// 多语言加载
// \think\middleware\LoadLangPack::class,
// Session初始化
// \think\middleware\SessionInit::class,
// 开启跨域
\think\middleware\AllowCrossDomain::class
];
OPTIONS请求处理
创建 OptionsHandle中间件,如果请求时OPTIONS时直接返回200状态
<?php
declare (strict_types=1);
namespace app\middleware;
use think\Request;
use think\Response;
class OptionsHandle
{
/**
* 处理OPTIONS请求
* @param Request $request
* @param \Closure $next
* @return Response
* @throws \app\api\common\BaseException
*/
public function handle($request, \Closure $next)
{
if (request()->method() == 'OPTIONS') {
ApiException('OPTIONS', ERR_DEFAULT, 200);
}
return $next($request);
}
}
在全局中间件定义文件中新增一行
// 处理OPTIONS
\app\middleware\OptionsHandle::class
可解决浏览器在发送OPTIONS预检时,接口返回非200状态导致请求终止的情况,因为浏览器预检行为无法人工干涉,如果接口是通过请求头鉴权,会导致后端鉴权失败返回非200状态
更多...