Laravel 8 作为 api 服务器时,如果想要使用 Postman 提交数据,表单验证异常时返回 json 格式数据
方法一:设置请求头 Accept: application/json
方法二:设置请求头 X-Requested-With: XMLHttpRequest
方法三:在 App\Exceptions\Handler 文件中添加如下方法:
/** | |
* Create a response object from the given validation exception. | |
* | |
* @param \Illuminate\Validation\ValidationException $e | |
* @param \Illuminate\Http\Request $request | |
* @return \Symfony\Component\HttpFoundation\Response | |
*/ | |
protected function convertValidationExceptionToResponse(ValidationException $e, $request) | |
{ | |
if ($e->response) { | |
return $e->response; | |
} | |
return response()->json([ | |
// 自定义返回信息 | |
'message' => '提交的数据无效', | |
'errors' => $e->errors(), | |
], $e->status); | |
} |