- 终端中输入命令 新建一个Cross中间件
php think make:middleware Cross
* 设置跨域
* @param $request
* @param \Closure $next
* @return mixed|void
*/
public function handle($request, \Closure $next)
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Max-Age: 1800');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
header('Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, Token');
if (strtoupper($request->method()) == "OPTIONS") {
return Response::create()->send();
}
return $next($request);
}
- 在app下的middleware.php中使用中间件
<?php
// 全局中间件定义文件
return [
// 全局请求缓存
// \think\middleware\CheckRequestCache::class,
// 多语言加载
// \think\middleware\LoadLangPack::class,
// Session初始化
// \think\middleware\SessionInit::class
//解决跨域问题 自定义Cross中间件
\app\middleware\Cross::class
];