Laravel 5.5 - 使用POST方法时的MethodNotAllowedHttpException

时间:2017-09-17 01:41:17

标签: php laravel laravel-5 routing routes

我创建了过滤器来从数据库中获取数据。当我使用GET方法时它可以工作但是使用POST方法我得到错误:

  

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException

我花了几个小时寻找解决方案,但似乎我在这里遗漏了一些东西。

对于测试我试图直接在路线中获得结果,但它仍然是同样的问题。

这很有效。

<?php
use App\test;
Route::get('/', function () {
    $test = test::all();
return $test;
});

这不起作用。

<?php
use App\test;
Route::post('/', function () {
    $test = test::all();
return $test;
});

4 个答案:

答案 0 :(得分:2)

这个

use App\test;
Route::post('/', function () {
    $test = test::all();
return $test;
});

应始终是Request的实例,因此您无法直接在浏览器中访问它,例如GET您必须向其发布一些表单数据。因此,最好将其重命名为某些内容,例如:

use App\test;

Route::post('/test', function (Request $request) {
    $test = test::all();
return $test;
});

$request保存表单数据

答案 1 :(得分:2)

Route::get()Route::post()正在为指定的http方法定义路由处理程序。

如果您只定义此路线:

Route::post('/', function () {
    $test = test::all();
    return $test;
});

然后,您必须确保对该URL的所有调用都使用POST方法。如果您使用GET方法向该URL发出请求,您将获得MethodNotAllowedHttpException异常,因为您只定义了POST方法处理程序。

答案 2 :(得分:1)

您可能会忘记{{csrf_field()}}。将其添加到表单中。

如果您在没有csrf的情况下发布数据,请在laravel 5.5中看到此错误。

答案 3 :(得分:0)

请注意,如果您正在编写发布路线,那么在测试时请确保您将数据发布到页面,否则会出错。

发布路由无法通过调用url进行测试,该方法应该发布。如果您使用邮递员检查路由URI,它将起作用。