我是第一次使用Slim框架创建一个api.
如果找不到网址,我想返回一个特定的响应.
我使用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);