跨域配置
跨域介绍
通过中间件+路由配置实现跨域 如果在线上环境使用,请将验证码模式设置为 redis 模式
跨域中间件
1、系统已内置跨域中间件CrossDomain.php
, 内容如下:
php
namespace plugin\saiadmin\app\middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
/**
* 跨域中间件
*/
class CrossDomain implements MiddlewareInterface
{
public function process(Request $request, callable $handler) : Response
{
// 如果是options请求则返回一个空响应,否则继续向洋葱芯穿越,并得到一个响应
$response = $request->method() == 'OPTIONS' ? response('') : $handler($request);
// 给响应添加跨域相关的http头
$response->withHeaders([
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Origin' => $request->header('origin', '*'),
'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
]);
return $response;
}
}
2、如果使自己的插件或者应用
全局跨域,则需要在插件或者应用
的config/middleware.php
中配置:
php
use plugin\saiadmin\app\middleware\CrossDomain;
return [
'' => [
CrossDomain::class,
]
];
3、在插件或者应用
路由中配置,文件位置:config/route.php
:
php
use Webman\Route;
Route::fallback(function() {
$response = request()->method() == 'OPTIONS' ? response('') : json(['code' => 400, 'message' => '异常请求']);
$response->withHeaders([
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Origin' => request()->header('origin', '*'),
'Access-Control-Allow-Methods' => request()->header('access-control-request-method', '*'),
'Access-Control-Allow-Headers' => request()->header('access-control-request-headers', '*'),
]);
return $response;
});
// 此处配置的路由全部能够跨域
Route::group('/api', function () {
// 数据字典
Route::get("/common/dict",[\plugin\saiuser\app\controller\CommonController::class, 'dictData']);
Route::get("/common/dictAll",[\plugin\saiuser\app\controller\CommonController::class, 'dictAll']);
......