laravel 404页面不存在,请返回首页

fslejnso  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(139)

因此,当用户在存在的路由上随机键入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);
            }
        });
    }

但它不起作用

qoefvg9y

qoefvg9y1#

在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

相关问题