简体   繁体   English

如何将 CORS 中间件添加到自定义 Laravel Nova 工具中定义的路由?

[英]How can I add CORS middleware to routes defined in custom Laravel Nova tool?

I'm building a headless cms using laravel nova and vuejs.我正在使用 laravel nova 和 vuejs 构建一个无头 cms。

I'm having an issue with trying to register the excellent CORS middleware from https://github.com/barryvdh/laravel-cors .我在尝试从https://github.com/barryvdh/laravel-cors注册优秀的 CORS 中间件时遇到问题。 I can get this working from the main app but I would like to add this as a dependency to my custom nova tool.我可以从主应用程序中获得它,但我想将它作为依赖项添加到我的自定义 nova 工具中。

I just can't figure out how to do this.我只是不知道如何做到这一点。

I've tried adding the middleware in the routes function generated by the artisan nova:tool command.我已经尝试在由artisan nova:tool命令生成的路由函数中添加中间件。

/**
 * Register the tool's routes.
 *
 * @return void
 */
protected function routes()
{
    if ($this->app->routesAreCached()) {
        return;
    }

    Route::middleware(\Barryvdh\Cors\HandleCors::class)
       ->prefix('api/meta-blog')
       ->group(__DIR__.'/../routes/api.php');
}

But I get an error Class Barryvdh\\Cors\\HandleCors does not exist from vendor/laravel/framework/src/Illuminate/Container/Container.php when I hit any of the api paths.但是当我点击任何 api 路径时,我收到一个错误Class Barryvdh\\Cors\\HandleCors does not exist from vendor/laravel/framework/src/Illuminate/Container/Container.php

I think this is because the middleware is not registered with the main app.我认为这是因为中间件未在主应用程序中注册。 I'm looking to find out how to make this 3rd party nova tool dependency work with the main laravel routing system.我正在寻找如何使这个 3rd 方 nova 工具依赖项与主要的 Laravel 路由系统一起工作。

I have successfully used other 3rd party packages with success.我已经成功地成功使用了其他 3rd 方软件包。 But not this one.但不是这个。 I can confirm that the package exists and has been loaded in my custom tools autoload file.我可以确认该包存在并已加载到我的自定义工具自动加载文件中。

Thanks in advance.提前致谢。

I solved this.我解决了这个问题。

In the boot function we can push a middleware to the api group.在 boot 函数中,我们可以将中间件推送到 api 组。

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    ...

    $router = $this->app['router'];
    $router->pushMiddlewareToGroup('api', Barryvdh\Cors\HandleCors::class);
}

Then in the routes function然后在路由功能中

/**
 * Register the tool's routes.
 *
 * @return void
 */
protected function routes()
{
    if ($this->app->routesAreCached()) {
        return;
    }

    Route::prefix('api/meta-blog')
        ->group(__DIR__.'/../routes/api.php');
}

Hope this helps someone else.希望这对其他人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM