laravel 为什么我会收到 422 错误代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37146559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting a 422 error code?
提问by Donnie
I am making a POST request, but unable to get anything besides a 422 response.
我正在发出 POST 请求,但除了 422 响应之外无法获得任何信息。
Vue.js client code:
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 Routes:
Laravel 路线:
Route::post('/office-depot-register', ['uses' => 'OfficeDepotController@register', 'as' => 'office-depot-register']);
Laravel Controller:
Laravel 控制器:
public function register(Request $request)
{
$this->validate($request, [
'companyName' => 'required',
// ...
]);
// ...
}
采纳答案by Brandon Anzaldi
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.
Laravel 允许您在它接受的字段上定义某些验证。如果这些验证失败,它将返回HTTP 422 - Unprocessable Entity
. 在您的特定情况下,您似乎使用空骨架对象未能通过自己的验证测试,因为它companyName
是必需的,而空字符串未通过所需的验证。
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: '[email protected]',
numberOfOffices: 1,
numberOfEmployees: 2,
}
}