为什么会收到422错误代码?

Don*_*nie 7 laravel vue.js laravel-5.2 vue-resource

我正在发出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);

      });
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

Laravel路线:

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

Laravel控制器:

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

Bra*_*ldi 15

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,
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 您如何优雅地捕获此错误并使用返回的 JSON 响应显示错误,这样 422 就不会出现,或者这样可以吗? (3认同)