POST路由收到非法请求时,如何返回自定义JSON响应?
自定义POST路由的405错误JSON响应
我有一个POST类型的路由,希望当有人发起GET请求时,返回自定义的JSON消息,而不是框架默认的如下提示:
MethodNotAllowedException MethodNotAllowedHttpException
HTTP 405 Method Not Allowed
No route found for "GET http://localhost:8000/api/doSearch.json": Method Not Allowed (Allow: POST)
我尝试了下面的代码,但在路由相关文件层面直接崩溃了:
try { // 检查请求是否为POST方法 if(!$request->isMethod('POST')) { $isError = true; $errorString = "Method Not Allowed: Only POST requests are allowed for this resource"; $httpCode = 405; } } catch(MethodNotAllowedHttpException $mna) { $isError = true; $errorString = "Method Not Allowed"; }
解决方案
方法1:路由层面直接处理
直接在路由文件中同时注册GET和POST方法,针对GET请求返回自定义JSON响应:
use Illuminate\Http\Request; Route::match(['get', 'post'], '/api/doSearch.json', function(Request $request) { if ($request->isMethod('get')) { return response()->json([ 'error' => true, 'message' => 'Method Not Allowed: Only POST requests are allowed for this resource' ], 405); } // 此处编写POST请求的业务逻辑 // return response()->json(...); });
方法2:全局异常捕获处理
在项目的异常处理器中捕获MethodNotAllowedHttpException,针对特定路由返回自定义JSON:
修改app/Exceptions/Handler.php文件:
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; public function register() { $this->renderable(function (MethodNotAllowedHttpException $e, $request) { // 判断当前请求是否是目标路由 if ($request->is('api/doSearch.json')) { return response()->json([ 'error' => true, 'message' => 'Method Not Allowed: Only POST requests are allowed for this resource' ], 405); } }); }
为什么之前的代码会崩溃?
当发起GET请求时,框架在路由匹配阶段就会抛出MethodNotAllowedHttpException,根本不会进入你写的try-catch代码块,所以你的捕获逻辑完全没生效。另外代码中只定义了变量但未返回响应,也会导致程序异常。
内容的提问来源于stack exchange,提问作者Volatil3
相关产品推荐
相关产品推荐

