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

标签 laravel laravel-5.2 vue.js 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);

      });
    }
  }
});

Laravel 路由:

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

Laravel Controller :

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

    // ...
}

最佳答案

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

关于laravel - 为什么我会收到 422 错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37146559/

相关文章:

php - Elasticsearch [查询 bool 值必须匹配]执行或运算,而不是与运算符

php - Laravel Eloquent - 获取相关模型的最后插入

javascript - 无样式内容 vuejs 的 Flash

vue.js - Vue JS 中根据 ID 悬停时显示 Div

azure - Passport-azure-ad 与 OAuth 2.0 使用 VueJS SPA 和 Vuex 的授权代码流(使用 PKCE)

jquery - 来自 SQL Server 的位置名称和传单 map 上的绘图

php - 如何使用变量名调用类?

laravel - 在包上使用模型

php - 如何在 laravel 5.2 框架中记录每个响应

laravel - Laravel Eloquent一次插入带有时间戳的3行