为什么会收到422错误代码? [英] Why am I getting a 422 error code?

查看:5268
本文介绍了为什么会收到422错误代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在发出POST请求,但是除了422响应之外什么都没得到.

I am making a POST request, but unable to get anything besides a 422 response.

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允许您在其接受的字段上定义某些验证.如果您未通过这些验证,它将返回HTTP 422 - Unprocessable Entity.在您的特定情况下,您似乎无法通过一个空的骨架对象进行自己的验证测试,因为需要companyName,并且空字符串不能通过所需的验证.

Laravel allows you to define certain validations on fields it accepts. If you fail these validations, it will return HTTP 422 - Unprocessable Entity. In your particular case, it appears that you're failing your own validation tests with an empty skeleton object, since companyName is required, and an empty string does not pass the required validation.

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

Assuming the other fields are similarly validated, a populated data object should solve your issue.

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,
  }
}

这篇关于为什么会收到422错误代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆