我尝试使用 Laravel 和 Vue 验证后端的表单数据,但没有收到 422 响应。
这是我的 Controller 功能:
$this->validate($request, [
'name' => 'required',
'city' => 'required',
'state' => 'required'
]);
$location = $request->isMethod('put') ?
Locations::findOrFail($request->id) : new Locations;
$location->id = $request->input('id');
$location->name = $request->input('name');
$location->address = $request->input('address');
$location->city = $request->input('city');
$location->state = $request->input('state');
$location->zip = $request->input('zip');
$location->phone = $request->input('phone');
if($location->save())
{
return new LocationsResource($location);
}
这是 Vue 方法:
addLocation() {
if (this.edit === false) {
// Add
fetch('api/location', {
method: 'post',
body: JSON.stringify(this.location),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then(data => {
this.clearForm();
alert('Location Added');
this.fetchArticles();
});
} else {
// Update
fetch('api/location', {
method: 'put',
body: JSON.stringify(this.location),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then(data => {
this.clearForm();
alert('Locations Updated');
this.fetchArticles();
})
}
}
表格如下:
<form @submit.prevent="addLocation" class="mb-3">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" v-model="location.name">
<input type="text" class="form-control" placeholder="City" v-model="location.city">
<input type="text" class="form-control" placeholder="State" v-model="location.state">
</div>
<button type="submit" class="btn btn-light btn-block">Save</button>
</form>
当我打开检查器并进入 Network->XHR 时,我得到了 CRUD 的所有正确状态代码,但是当表单应该失败时,我没有得到 422 HTTP 状态代码。当我提交没有数据的表单时,它不会保存,但不会发送状态代码,也没有响应向用户提供反馈。感谢您的帮助。
最佳答案
我必须将 "accept": "application/json"添加到 addLocation 方法的 header 中。
关于javascript - Vue 和 Laravel 表单验证未返回 422 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52652492/