在Laravel中为POST方法路由回退?

时间:2019-04-02 07:27:56

标签: laravel routes

有没有一种方法可以检查后备方法的路线回退?此代码适用于我的路线文件中的任何获取url,即,如果我键入并输入了错误的GET URL,则会收到此响应(“找不到页面”。)。

有没有一种方法可以检查POST网址?

Route::fallback(function(){
    return response()->json([
        'status'    => false,
        'message'   => 'Page Not Found.',
    ], 404);
});

4 个答案:

答案 0 :(得分:2)

use Request;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

在app / Exceptions / Handler.php中替换渲染功能

public function render($request, Exception $exception)
    {
        if (Request::isMethod('post') && $exception instanceof MethodNotAllowedHttpException) {
            return response()->json([
                'message' => 'Page Not Found',
                'status' => false
                ], 500
            );
        }
        return parent::render($request, $exception);
    }

或者在您同时希望NotFound和MethodNotAllowed

public function render($request, Exception $exception)
    {
        if ((Request::isMethod('post') && $exception instanceof MethodNotAllowedHttpException) || (Request::isMethod('post') && $exception instanceof NotFoundHttpException)) {
            return response()->json([
                'message' => 'Page Not Found',
                'status' => false
                ], 500
            );
        }
        return parent::render($request, $exception);
    }

答案 1 :(得分:2)

在route / api.php末尾定义自定义后备路由

Route::any('{any}', function(){
    return response()->json([
        'status'    => false,
        'message'   => 'Page Not Found.',
    ], 404);
})->where('any', '.*');

答案 2 :(得分:1)

将此脚本放在路由文件的末尾。

Route::any('{url?}/{sub_url?}', function(){
    return response()->json([
        'status'    => false,
        'message'   => 'Page Not Found.',
    ], 404);
})

它会自动检测是否有人尝试打以下任何其他路线。

laravel_project_path/public/any_string
laravel_project_path/public/any_string/any_string

答案 3 :(得分:0)

您可以使用给定的方法检查POST网址。

Route::fallback(function(){
    return \Response::view('errors.404');
});
相关问题