Vue和Laravel表单验证未返回422响应

时间:2018-10-04 17:34:58

标签: javascript ajax laravel validation vue.js

我正在尝试使用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状态代码。当我提交没有数据的表单时,它不会保存,但是不会发送任何状态代码,因此没有响应可以向用户提供反馈。感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

$this->validate($request, [
    'name' => 'required',
    'city' => 'required',
    'state' => 'required'
    ]);

我从未见过这样的用法。我认为控制器没有验证功能。试试这个:

$request->validate([
    'name' => 'required',
    'city' => 'required',
    'state' => 'required'
    ]);

答案 1 :(得分:0)

我必须在addLocation方法的标题中添加“ accept”:“ application / json”。