laravel报错:post到不存在的路由时触发MethodNotAllowedHttpException(10.27.0)
一,报错信息
post到不存在的路由时,会触发MethodNotAllowedHttpException,提示信息:
The POST method is not supported for route login/login. Supported methods: GET, HEAD."
The POST method is not supported for route login/login. Supported methods: GET, HEAD.
它没有触发我们配置的404提示
二,解决:修改handler.php
app\Exceptions\Handler.php
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
<?phpnamespace App\Exceptions;use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;use Throwable;class Handler extends ExceptionHandler{ /** * The list of the inputs that are never flashed to the session on validation exceptions. * * @var array<int, string> */ protected $dontFlash = [ 'current_password', 'password', 'password_confirmation', ]; /** * Register the exception handling callbacks for the application. */ public function register(): void { $this->reportable(function (Throwable $e) { //$status = $e->getStatusCode(); //var_dump($status); }); } //重写render public function render($request, Throwable $e) { if (env('APP_DEBUG')) { return parent::render($request, $e); } //判断如果是MethodNotAllowedHttpException时,返回404错误 if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) { return response()->json([ 'code' => '404', 'msg' => '访问地址错误', ]); } //返回 return response()->json([ 'code' => $e->getCode(), 'msg' => $e->getMessage(), ]); }} |
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/10/31/laravel-bao-cuo-post-dao-bu-cun-zai-de-lu-you-shi-chu-fa-methodnotallowedhttpexception-10-27/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
三,测试效果
1,未设置前:

2,设置后:

四,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0

浙公网安备 33010602011771号