Laravel 中 POST 方法的路由回退?

azm*_*hah 5 routes laravel

有没有办法检查 post 方法的路由回退?此代码适用于我的路由文件中的任何获取 url,即,如果我输入错误的 GET url,我会收到此响应(“找不到页面。”)。

有没有办法检查 POST url 是否相同?

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

小智 15

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

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


Aka*_*rma 5

use Request;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Run Code Online (Sandbox Code Playgroud)

在 app/Exceptions/Handler.php 中替换 render 函数

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);
    }
Run Code Online (Sandbox Code Playgroud)

或者如果您同时想要 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);
    }
Run Code Online (Sandbox Code Playgroud)