【问题标题】:Laravel returns MethodNotAllowedHttpException on routing does not existLaravel 在路由不存在时返回 MethodNotAllowedHttpException
【发布时间】:2019-07-27 09:07:17
【问题描述】:

我在 laravel 5.7 中创建了购买商品的路线

Route::post('/buy/item', "userController@buy_item")->name('buy_item_form');

一切正常,但是当我刷新页面(替换为 GET 请求)时,我得到了一个 MethodNotAllowedHttpException。 GET 路由不存在,它必须返回 404 错误。 我不明白为什么它会返回这个异常。

【问题讨论】:

    标签: php laravel post get routing


    【解决方案1】:

    你正在使用一个帖子,你有一个 @csrf 令牌。当您单击刷新时,您正在执行 GET 方法而不是帖子,因此您获得的方法不允许异常。如果您不发送数据,您可以将其更改为 get [Route::get] 方法。

    如果您想接受 2 种方法 [post,get] 以获得更好的体验并管理可能的错误。您可以接受路线上的 2 种方法,例如:

    Route::match(array('GET','POST'),'/buy/item', 'userController@buy_item')->name('buy_item_form');
    

    在控制器上,根据方法定义要做什么。

    if (Request::isMethod('get')){
        // redirect user
    }
    
    if (Request::isMethod('post')){
        // do logic for post method
    }
    
    

    【讨论】:

    • 我没有创建 GET 路由。那么为什么如果路由不存在,我会在 GET 请求上遇到异常。这应该返回一个 404 错误。
    • 当你刷新或者跳转到一个页面是一个get方法,如果你提交数据并且在表单上设置方法post,它会post info而不是get . w3schools.com/tags/ref_httpmethods.asp
    • 我的意思是我创建了一个 Post Route,当我在浏览器的 url 地址栏上写 post route 的 url 时(发出获取请求),它返回一个异常而不是 404 错误。我可以制作一条 get route 来做 abort(404) 但不是必须发生吗?
    • 将此添加到您的代码中,您将看到您正在执行刷新 Route::get('/buy/item', function(){ return "Get Request"; }) ;
    • 我可以这样做:Route::get('/buy/item', function(){return abort(404)});但我的问题是为什么不会自动发生。
    猜你喜欢
    • 2021-01-25
    • 2015-03-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 2017-11-14
    • 2018-04-13
    • 2016-02-12
    • 2015-12-22
    相关资源
    最近更新 更多