【发布时间】:2019-03-10 04:28:37
【问题描述】:
我正在尝试使用 Laravel 和 Vue 在后端验证表单数据,但没有收到 422 响应。
这是在我的控制器功能中:
$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 状态代码。当我提交没有数据的表单时,它不保存,但没有发送状态码,没有响应给用户反馈。感谢您的帮助。
【问题讨论】:
-
你在 XHR 中的反应是什么?
-
当我点击保存并故意验证失败时,什么都没有发生,我没有得到回应,没有反馈。
-
如果没有响应,你怎么能说“验证失败”?
标签: javascript ajax laravel validation vue.js