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

标签 javascript ajax laravel validation vue.js

我尝试使用 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/

相关文章:

jquery - jquery ajax 中的 DataType 与 ContentType

javascript - 无法根据 ajax 请求在 php 中获取 $_POST 值

javascript - cfajaxproxy 的简单表单不起作用

php - Laravel验证数字多维数组

javascript - append 数据属性时无法识别的表达式

javascript - 以动态深度访问嵌套数组

php - 在 Laravel 5 迁移中更新表并添加数据

json - laravel中以json对象传递数据库数据

javascript - 如何匹配可能有或没有后缀的 JS 正则表达式

javascript - 如果该页面有必要加载 js/css