gpt4 book ai didi

php - slim 的框架方法 notFound 不是有效的方法

转载 作者:搜寻专家 更新时间:2023-10-31 20:35:09 25 4
gpt4 key购买 nike

我是第一次使用 Slim 框架创建一个 api。

如果找不到 url,我想返回一个特定的响应。

我使用Slim框架的notFound函数如下:

$app->notFound(function () use ($app) {
$res = array("msg"=>"page not found");
$response->getBody()->write(json_encode($res));
return $response;
});

但是当我在我的 php 页面中添加这行代码时,它显示以下错误:

Fatal error: Uncaught exception 'BadMethodCallException' with message 'Method notFound is not a valid method' in C:\wamp\www\api\vendor\slim\slim\Slim\App.php on line 129

BadMethodCallException: Method notFound is not a valid method in C:\wamp\www\api\vendor\slim\slim\Slim\App.php on line 129

最佳答案

似乎您正在使用 Slim 3 和 Slim 2 的一些代码。
在 3 中,您可以通过在容器中添加处理程序 ( mode details here ) 或添加中间件来实现:
编辑 - 正如@geggleto 指出的那样,我忘了提及对于下面的代码,您还应该设置 $settings['determineRouteBeforeAppMiddleware'] = true

/**
* check if route exists
*/
$middleware = function (Request $request, Response $response, $next) {

if (!$request->getAttribute('route')) {
$res = array("msg"=>"page not found");
$response->getBody()->write(json_encode($res));
return $response;
}

return $next($request, $response);
};
$app->add($middleware);

关于php - slim 的框架方法 notFound 不是有效的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37553824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com