tp51 api接口跨域处理-middleware方式
1、创建中间件、终端执行命令生成(也可手动)
php think make:middleware Cors
<?php
namespace app\http\middleware;
class Cors
{
public function handle($request, \Closure $next)
{
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Authorization, Sec-Fetch-Mode, DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, If-Match, If-None-Match, If-Unmodified-Since, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type,token, Accept-Language, Origin, Accept-Encoding");
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
header('Access-Control-Max-Age: 1728000');
if (strtoupper($request->method()) == "OPTIONS") {
return response();
}
return $next($request);
}
}
2、引入中间件
当前模块下建立middleware.php,然后引入刚才建立的中间件Cors
<?php
return [
app\http\middleware\Cors::class,
];
3、路由分组
<?php
Route::group('api', function () {
Route::get('/getUserList', 'api/index/getUserList');
})->middleware('Cors');