因此,当用户在存在的路由上随机键入URL时,他们会收到一条错误消息:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
在做了一些搜索之后,我能找到的所有帖子都建议更改App\Exceptions\Handler中的render函数,并将其更改为:
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);
}
});
}
但它不起作用
1条答案
按热度按时间qoefvg9y1#
在Laravel上的较新版本中,您可以添加
\App\Exceptions\Handler
类的register
方法内的此行如果要处理NotFoundException,应使用
有关Laravel文档的更多详细答案,请访问:https://laravel.com/docs/9.x/errors#rendering-exceptions