Dingo API 是 Laravel 框架的一个扩展包,用于快速构建 RESTful API。按多个域分组是指将 API 路由根据不同的域名进行分组管理,这在多租户系统或需要为不同子域名提供不同 API 的场景中非常有用。
首先在 config/api.php
中配置多个域名:
'domains' => [
'api.example.com' => [
'version' => 'v1',
'prefix' => 'api',
],
'mobile.api.example.com' => [
'version' => 'v2',
'prefix' => 'mobile',
],
],
在 routes/api.php
中按域名分组路由:
$api = app('Dingo\Api\Routing\Router');
// 主域名路由
$api->version('v1', ['domain' => 'api.example.com'], function ($api) {
$api->group(['namespace' => 'App\Http\Controllers\Api\V1'], function ($api) {
$api->get('users', 'UserController@index');
$api->post('users', 'UserController@store');
});
});
// 移动子域名路由
$api->version('v2', ['domain' => 'mobile.api.example.com'], function ($api) {
$api->group(['namespace' => 'App\Http\Controllers\Api\V2'], function ($api) {
$api->get('users', 'UserController@index');
$api->post('users', 'UserController@store');
});
});
对于需要动态处理域名的情况:
$api->version('v1', function ($api) {
$api->group(['domain' => '{account}.api.example.com'], function ($api) {
$api->get('profile', function ($account) {
// 根据 $account 处理逻辑
return response()->json(['account' => $account]);
});
});
});
原因:
解决方案:
config/api.php
中的域名配置php artisan route:clear
解决方案: 为不同域名配置 CORS 中间件:
// 在 App\Http\Middleware 创建 CorsMiddleware
public function handle($request, Closure $next)
{
$response = $next($request);
$origin = $request->header('Origin');
$allowedDomains = ['api.example.com', 'mobile.api.example.com'];
if (in_array(parse_url($origin, PHP_URL_HOST), $allowedDomains)) {
$response->header('Access-Control-Allow-Origin', $origin);
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
$response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
return $response;
}
解决方案: 在路由中使用中间件验证域名参数:
$api->version('v1', ['domain' => '{tenant}.api.example.com'], function ($api) {
$api->group(['middleware' => 'validate.tenant'], function ($api) {
// 路由定义
});
});
通过以上方式,可以灵活地在 Laravel 中使用 Dingo API 实现按多个域分组的功能,满足复杂业务场景的需求。
没有搜到相关的文章