RouteCollection.php第218行Laravel 5.2中的MethodNotAllowedHttpException

时间:2016-08-19 11:29:48

标签: php laravel laravel-5.2 laravel-routing

我必须通过浏览器访问PUT路由并获取json对象,但是L5.2向我显示了一个MethodNotAllowedHttpException错误,我该怎么做才能解决这个问题?

我的网址http://laravel5.restapi.dev/a?_method=put

我的路线:列表

route.php

<?php

Route::put('/a', function () {
   return view('welcome');
});

输出

Whoops, looks like something went wrong.

MethodNotAllowedHttpException in RouteCollection.php line 218:
in RouteCollection.php line 218
at RouteCollection->methodNotAllowed(array('PUT')) in RouteCollection.php line 205
at RouteCollection->getRouteForMethods(object(Request), array('PUT')) in RouteCollection.php line 158
at RouteCollection->match(object(Request)) in Router.php line 821
at Router->findRoute(object(Request)) in Router.php line 691
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Debugbar.php line 49
at Debugbar->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Debugbar), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 53

3 个答案:

答案 0 :(得分:1)

PUT方法仅在您的表单方法为POST时才有效,然后您添加带有值PUT的_method输入字段。

<form method="post">
    <input type="hidden" name="_method" value="PUT">
</form>

答案 1 :(得分:1)

由于您正在使用Route::post($uri, $callback),因此不允许PUT请求。

您需要将路线指定为Route::put($uri, $callback)或(如果您还需要匹配其他请求):

Route::match(['post', 'put'], '/a', function () {
    // for post & put requests
});

Route::any('/a', function () {
    // for all methods
});

如评论和其他答案中所述,PUT请求必须是带有附加参数_method=PUT的POST请求。

请参阅:https://laravel.com/docs/5.2/routing#basic-routing

答案 2 :(得分:0)

您也可以使用

    {{ method_field('PUT') }}
使用method = post在表单中

。以便method_field将其转换为put

然后在您的routes.php

     Route::put(.....);

    Route::any(...);