cakephp-4.x - 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');
});
解决方案
这是我的中间件的问题。
我知道 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;
}
}
推荐阅读
- socket.io - 未捕获的类型错误:无法读取未定义 socket.io.client 的属性“sid”
- database - 随着文档大小的增加,文档需要在 mongo 4.4 中重新定位的频率
- jquery - jQUery 5000+ 行 .append() 改进?
- javascript - 带有值的 Javascript 数组
- java - 编译时间与运行时间(通过查看代码)
- azure - ARM模板:如何以数组格式读取输出结果
- java - IO 错误:将 oracle DB 作为 docker 容器运行并尝试通过 Tomcat 连接时,网络适配器无法建立连接
- kubernetes - 无法使用 Istio 网关访问 Kubernetes 集群
- python - STAN RuntimeError:初始化失败
- python - 代替 。在 json 文件中使用 _ 并使用 python 将其写入表