Why am I getting a 422 error code?

不羁岁月 提交于 2019-12-12 10:37:17

问题


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

Vue.js client code:

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 Routes:

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

Laravel Controller:

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

    // ...
}

回答1:


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


来源:https://stackoverflow.com/questions/37146559/why-am-i-getting-a-422-error-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!