首页 > 解决方案 > 使用前缀时路由 URI 通配符

问题描述

在我决定将前端文件移动到前缀 (/crm) 后面之前,我一直在成功地为我的根路径 (/) 使用路由通配符。之后我得到 404 并且不知道如何解决它。我需要通配符作为我的 Javascript 前端路由 (/crm/orders/details/12345) 的全部内容,否则会导致 404。

因此,当我删除prefix('crm')时,使用以下代码设置的所有内容都可以正常工作。或者当我删除{any}加上匹配的正则表达式时,它在一级深度路由上部分工作(/crm有效,但/crm/orders无效)。

但是当我同时拥有前缀和通配符时,/crm给了我一个 404。

我需要如何配置它?

作品

提供者/RouteServiceProvider.php:

Route::namespace('App\Http\Controllers')
  ->group(base_path('routes/crm.php'));

路线/crm.php

Route::get('/{any}', function ()
{
    return view('crm');
})->where('any', '.*');

不工作

提供者/RouteServiceProvider.php:

Route::prefix('crm')
  ->namespace('App\Http\Controllers')
  ->group(base_path('routes/crm.php'));

路线/crm.php

Route::get('/{any}', function ()
{
    return view('crm');
})->where('any', '.*');

php artisan route:list的输出如下

| Domain | Method | URI |Name | Action | Middleware  |
*snap*
| | GET|HEAD | crm/{any} | | Closure | |
*snap*

标签: phplaravellaravel-routing

解决方案


您需要配置{any}为可选参数。在您的特定情况下,该路线只会捕获crm/something路线(其中某些东西可以是一个或多个段)。

Route::prefix('crm')->group(function () {
    Route::get('/{any?}', function () {
        dd("I am here");
    })->where('any', '.*');
});

但是,如果您添加{any}as 可选,它也会捕获/crm. 这是你想要的?


推荐阅读