【问题标题】:Middleware to redirect users if they type POST route in URL Laravel如果用户在 URL Laravel 中键入 POST 路由,中间件会重定向用户
【发布时间】:2019-07-28 08:18:07
【问题描述】:

到目前为止,当我的用户在 URL 中输入 POST 路由时,它会显示错误消息 The GET method is not supported for this route. Supported methods: POST.。我想编写一个中间件,如果他们尝试去任何 POST 路由,它将重定向用户。我尝试过以下操作:

我创建了一个RedirectIfPOST 中间件。这是它的代码:

<?php

namespace App\Http\Middleware;

use Closure;

class RedirectIfPOST
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        // Redirect if user tries accessing a POST route.

        return redirect('/');
    }
}

在我的Kernel.php 中,我将以下代码行添加到$routeMiddleware 数组中:

'post' => \App\Http\Middleware\RedirectIfPOST::class,

最后在我的web.php 中,我将我的所有POST 路由分组到我的中间件中,如下所示:

Route::group( ['middleware' => 'post'],function()
{

    Route::post('/signup', 'MainController@signup');

    Route::post('/login', 'MainController@authenticate');

    Route::post('/activate','ActiveController@activate');

});

如何解决此问题,以便将用户重定向到主页而不是看到错误?

编辑

我按照 Sherif Tarek 的建议做了以下操作:

我已经复制了我的POST 路线并制作了重复的路线GET。然后我将GET 路由分组到我的中间件中。所以现在我的web.php 看起来像这样:

Route::post('/signup', 'MainController@signup');

Route::post('/login', 'MainController@authenticate');

Route::post('/activate','ActiveController@activate');



Route::group( ['middleware' => 'post'],function()
{

    Route::get('/signup', 'MainController@signup');

    Route::get('/login', 'MainController@authenticate');

    Route::get('/activate','ActiveController@activate');

});

这样,如果用户尝试通过 URL 访问 POST 路由,我会将他们重定向到主页。

【问题讨论】:

    标签: laravel routing


    【解决方案1】:

    在这种情况下,异常是在执行请求调度管道之前抛出的,因此,您的中间件函数将不会被执行。您可以处理异常来归档您的目标,而不是使用中间件

    public function render($request, Exception $exception)
    {
       if($exception instanceof MethodNotAllowedHttpException && $request->isMethod('POST')){
           return redirect('/');
       }
       return parent::render($request, $exception);
    }
    

    我已经将上面的代码添加到 laravel App\Exceptions\Handler.php 文件中

    【讨论】:

    • 我已将 App\Exceptions\Handler.php 中的 render 函数更改为您示例中的函数,但在尝试访问 POTS 路由时仍然遇到相同的错误。我还有什么需要更改的代码吗?
    • 你能不能把Handler.php文件的内容贴出来,让我们看看有什么问题。并确保您已导入 Handler.php 文件顶部的 use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; 语句
    • 内容一样,我只是改了render函数的主体。我添加了use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;,但我仍然遇到同样的错误。上面的答案解决了我的问题,但感谢您的帮助。 :)
    【解决方案2】:

    问题是在中间件之前检查了Route,因为您可以在中间件中调用函数进行路由。解决您的问题的一种可能方法是复制您的路线,但将方法更改为GET,然后将中间件分配给它们,或者如果您选择这种方式,您可以redirect任何您想要的请求我认为有一个@ 987654324@ 将集中重定向路径或者如果你想有一个逻辑。

    【讨论】:

    • 效果很好
    猜你喜欢
    • 2019-11-20
    • 2019-10-05
    • 2017-06-19
    • 2019-12-23
    • 1970-01-01
    • 2015-07-08
    • 2016-03-10
    • 1970-01-01
    • 2011-11-17
    相关资源
    最近更新 更多