CakePHP 4.0.3 'A route matching X could not be found'中的路由问题



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

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

在服务器日志中它说:

2020-02-14 10:55:54 Error: [CakeRoutingExceptionMissingRouteException] 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 AppController
*
* @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');
});

这是我的中间件的问题。

我知道 Web 浏览器会发送预检请求,通过启用 CORS 标头,我认为我已经覆盖了自己。

然而

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

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

这就解释了为什么我的测试通过了。由于从未发出过 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;
}
}

相关内容

最新更新