首页 > 解决方案 > CakePHP 4.0.3 中的路由问题“找不到匹配 X 的路由”

问题描述

我正在制作一个 Web 应用程序,它有一个用 CakePHP 4.0.3 编写的后端 REST API 和一个用 Vue.js 2.6.11 编写的前端使用者,使用 axios 0.19.2 发出请求。

问题是我无法在我的任何端点上调用 DELETE 方法,也无法判断问题出在前端代码还是后端代码中。

在服务器日志中它说:

2020-02-14 10:55:54 Error: [Cake\Routing\Exception\MissingRouteException] A route matching "/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7" could not be found. in /var/www/html/vendor/cakephp/cakephp/src/Routing/RouteCollection.php on line 211
Exception Attributes: array (
  'url' => '/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7',
)
Stack Trace:
- /var/www/html/vendor/cakephp/cakephp/src/Routing/Router.php:227
- /var/www/html/vendor/cakephp/cakephp/src/Routing/Middleware/RoutingMiddleware.php:140
- /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php:58
- /var/www/html/vendor/cakephp/cakephp/src/Http/Server.php:90
- /var/www/html/webroot/index.php:40

Request URL: /meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7
Referer URL: http://localhost:8080/
Client IP: 172.19.0.1

意识到这只是一个路由问题,我bin/cake routes在终端中输入:

+------------------+-----------------+------------------------------------------------------------------------------------+
| Route name       | URI template    | Defaults                                                                           |
+------------------+-----------------+------------------------------------------------------------------------------------+
| mealplans:index  | /meal-plans     | {"_method":"GET","action":"index","controller":"MealPlans","plugin":null}          |
| mealplans:add    | /meal-plans     | {"_method":"POST","action":"add","controller":"MealPlans","plugin":null}           |
| mealplans:view   | /meal-plans/:id | {"_method":"GET","action":"view","controller":"MealPlans","plugin":null}           |
| mealplans:edit   | /meal-plans/:id | {"_method":["PUT","PATCH"],"action":"edit","controller":"MealPlans","plugin":null} |
| mealplans:delete | /meal-plans/:id | {"_method":"DELETE","action":"delete","controller":"MealPlans","plugin":null}      |
| meals:index      | /meals          | {"_method":"GET","action":"index","controller":"Meals","plugin":null}              |
| meals:add        | /meals          | {"_method":"POST","action":"add","controller":"Meals","plugin":null}               |
| meals:view       | /meals/:id      | {"_method":"GET","action":"view","controller":"Meals","plugin":null}               |
| meals:edit       | /meals/:id      | {"_method":["PUT","PATCH"],"action":"edit","controller":"Meals","plugin":null}     |
| meals:delete     | /meals/:id      | {"_method":"DELETE","action":"delete","controller":"Meals","plugin":null}          |
+------------------+-----------------+------------------------------------------------------------------------------------+

但正如您所看到的,它说路线已加载。

我写了一个测试,看看它是否能给我任何线索。测试应该失败了

class MealPlansControllerTest extends TestCase
{
    use IntegrationTestTrait;

    public $fixtures = [
        'app.MealPlans',
        'app.Meals'
    ];

    public function testDelete()
    {
        $this->assertCountRecords(1);

        $this->delete('/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7');
        $this->assertResponseCode(204);

        $this->assertCountRecords(0);
    }

    public function testDeleteInvalid()
    {
        $this->assertCountRecords(1);

        $this->delete('/meal-plans/14042f24-fa12-49d3-9bbe-91e57847a1c7');
        $this->assertResponseCode(404);

        $this->assertCountRecords(1);
    }

    private function assertCountRecords($expected)
    {
        $this->get('/meal-plans');
        $this->assertResponseCode(200);

        $body = json_decode((string) $this->_response->getBody(), true);
        $this->assertArrayHasKey('mealPlans', $body);
        $this->assertEquals($expected, count($body['mealPlans']));
    }

}

但是两个测试都通过了,所以它根本没有帮助。

所以现在我被困住了。我不知道发生了什么事。这可能很简单,但我看不到。

这些是违规路线:

/** @var RouteBuilder $routes */
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder &$builder) {
    $builder->setExtensions(['json']);
    $builder->resources('MealPlans');
    $builder->resources('Meals');
});

这是我正在尝试使用的控制器:

/**
 * Class MealPlansController
 * @package App\Controller
 *
 * @property MealPlansTable $MealPlans
 */
class MealPlansController extends AppController
{
    public $modelClass = 'MealPlans';

    public function delete($id)
    {
        try {
            $mealPlan = $this->MealPlans->get($id);
        } catch (RecordNotFoundException $e) {
            $this->response = $this->response->withStatus(404, __d('meal_plans', 'delete_404'));
            return $this->render();
        }
        if ($this->MealPlans->delete($mealPlan)) {
            $this->response = $this->response->withStatus(204, __d('meal_plans', 'delete_200'));
        } else {
            $this->response = $this->response->withStatus(500, __d('meal_plans', 'delete_500'));
        }
        return $this->render();
    }
}

前端调用如下所示:

deleteMealPlan (mealPlan) {
    axios.delete('http://localhost:11000/meal-plans/' + mealPlan.id)
        .then((response) => {
            console.log(response.statusText);
            this.$store.dispatch('planner/syncMealPlans').then(() => this.$forceUpdate());
        });
}

被调用的端点看起来像http://localhost:11000/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7

我可以很好地获取上述端点,我还没有测试 PUT 或 PATCH。

唯一其他相关的代码是我的中间件设置:

$middlewareQueue
    ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
    ->add(new AssetMiddleware([
        'cacheTime' => Configure::read('Asset.cacheTime'),
    ]))
    ->add(new RoutingMiddleware($this))
    ->add(new BodyParserMiddleware(['json' => true]))
    ->add(function (ServerRequest $request, Response $response, $next) {
        // Allow CORS
        return $next($request, $response)
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', '*')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
    });

标签: cakephp-4.x

解决方案


这是我的中间件的问题。

我知道 Web 浏览器会发送飞行前请求,并且通过启用 CORS 标头,我以为我已经覆盖了自己。

然而

无论请求方法如何,我都允许所有请求通过。这将使 OPTIONS 请求通过路由器。

当路由器试图解析请求并获得正确的路由时,它将无法找到任何在选项中定义了 OPTIONS 的路由_method并产生错误。

这就解释了为什么我的测试通过了。由于从未发出过 OPTIONS 请求,因此从未出现错误。

所以解决方案是,如果请求是 OPTIONS 请求,则提前返回

function (ServerRequest $request, Response $response, $next) {
    if ($request->getMethod() === 'OPTIONS') {
        return $response
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', '*')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
    } else {
        $response = $next($request, $response)
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', '*')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');

        return $response;
    }
}

推荐阅读