Laravel Api不从请求类发送所需的错误json消息
请求类Laravel Api不从请求类发送所需的错误json消息,laravel,laravel-5.7,laravel-5.8,Laravel,Laravel 5.7,Laravel 5.8,请求类 class LoginRequest extends FormRequest { public function wantsJson() { return true; } public function authorize() { return true; } public function rules() { $validators = [ 'email' =
class LoginRequest extends FormRequest
{
public function wantsJson() {
return true;
}
public function authorize() {
return true;
}
public function rules() {
$validators = [
'email' => 'required',
'password' => 'required'
];
return $validators;
}
public function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) {
if($validator->fails()) {
//print_r($validator->errors());
//die();
}
return parent::failedValidation($validator);
}
}
我有一个用Laravel编写的api。我试图通过邮递员扩展来测试验证。当我提交电子邮件和密码的一些值时,它就起作用了。我收到的消息是凭据是否存在
如果我不提交这些值,那么就不会返回json messagebag
我可以确认MessageBag中存在验证错误消息。这是截图。如果屏幕截图不清晰,请点击查看
另一件奇怪的事情是,返回的状态码是200
如果你需要更多信息,请告诉我
在我的情况下,我是这样设置我的Laravel API的 在我的
App\Exceptions\Handler
public function render($request, Exception $exception)
{
// return parent::render($request, $exception);
$rendered = parent::render($request, $exception);
if ($exception instanceof ValidationException) {
$json = [
'error' => $exception->validator->errors(),
'status_code' => $rendered->getStatusCode()
];
} elseif ($exception instanceof AuthorizationException) {
$json = [
'error' => 'You are not allowed to do this action.',
'status_code' => 403
];
}
else {
// Default to vague error to avoid revealing sensitive information
$json = [
'error' => (app()->environment() !== 'production')
? $exception->getMessage()
: 'An error has occurred.',
'status_code' => $exception->getCode()
];
}
return response()->json($json, $rendered->getStatusCode());
}
在顶部也导入这个
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
它有助于将错误格式化为JSON格式
我的LoginRequest
看起来像这样(简单)
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => 'required|email',
'password' => 'required'
];
}
}