【问题标题】:Why am I getting a 422 error code?为什么我会收到 422 错误代码?
【发布时间】:2016-09-05 21:44:19
【问题描述】:

我正在发出一个 POST 请求,但除了 422 响应之外什么也得不到。

Vue.js 客户端代码:

new Vue({
  el: '#app',

  data: {
    form: {
      companyName: '',
      street: '',
      city: '',
      state: '',
      zip: '',
      contactName: '',
      phone: '',
      email: '',
      numberOfOffices: 0,
      numberOfEmployees: 0,
    }
  },

  methods: {
    register: function() {
      this.$http.post('/office-depot-register', this.form).then(function (response) {

        // success callback
        console.log(response);

      }, function (response) {

        // error callback
        console.log(response);

      });
    }
  }
});

Laravel 路线:

Route::post('/office-depot-register', ['uses' => 'OfficeDepotController@register', 'as' => 'office-depot-register']);

Laravel 控制器:

public function register(Request $request)
{
    $this->validate($request, [
        'companyName' => 'required',
        // ...
    ]);

    // ...
}

【问题讨论】:

  • 据我所知,Laravel 发回 422 意味着请求没有满足验证要求。 (例如,缺少必填字段,其他验证失败)stackoverflow.com/questions/34966690/… 由于您需要 companyName,但将其作为空字符串,这很可能是导致您的问题的原因。
  • 就是这样。留下您的评论作为答案,我会接受。 ????
  • 很高兴我能帮上忙 :)

标签: laravel laravel-5.2 vue.js vue-resource


【解决方案1】:

Laravel 允许你在它接受的字段上定义某些验证。如果您未通过这些验证,它将返回 HTTP 422 - Unprocessable Entity。在您的特定情况下,您似乎无法使用空骨架对象进行自己的验证测试,因为需要companyName,而空字符串未通过所需的验证。

假设其他字段经过类似验证,填充的数据对象应该可以解决您的问题。

data: {
  form: {
    companyName: 'Dummy Company',
    street: '123 Example Street',
    city: 'Example',
    state: 'CA',
    zip: '90210',
    contactName: 'John Smith',
    phone: '310-555-0149',
    email: 'john@example.com',
    numberOfOffices: 1,
    numberOfEmployees: 2,
  }
}

【讨论】:

  • 您将如何优雅地捕获此错误并使用返回的 JSON 响应显示错误以使 422 不出现,或者这样可以吗?
  • @Robert Rocha 你可以做到.catch(error => { console.log(error.response) })
猜你喜欢
  • 1970-01-01
  • 2013-03-05
  • 2020-11-05
  • 2021-12-26
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 2021-07-12
  • 2020-11-05
相关资源
最近更新 更多