[英]MethodNotAllowedHttpException, redirect to 404 Laravel 9
因此,当用户在存在的路由上随机键入 URL 时,他们会收到一条错误消息:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
在做了一些搜索之后,我能找到的所有帖子都建议更改 App\Exceptions\Handler 中的渲染函数并将其更改为:
public function render($request, Exception $exception)
{
if($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException){
return abort('404');
}
return parent::render($request, $exception);
}
然而,随着 Laravel 的更新版本,这不再存在。 一篇文章提到在 routes\web.php 中添加这个:
Route::fallback( function () {
abort( 404 );
} );
这工作正常,但我不确定这是否是最好的方法/正确的地方? 还有其他替代方法吗?
我还尝试根据 Laravel 文档( https://laravel.com/docs/9.x/errors#rendering-exceptions )将 App\Exceptions\Handler 中的注册函数更改为此:
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
但它不起作用
在 Laravel 的较新版本中,您可以添加
$this->renderable(function (Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException $e) {
// do something
});
类\App\Exceptions\Handler
上的register
方法中的这一行
如果你想处理 NotFoundException 你应该使用
$this->renderable(function (Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
// do something
});
您可以在此处找到有关 Laravel 文档的更详细答案: https ://laravel.com/docs/9.x/errors#rendering-exceptions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.