【发布时间】:2017-03-29 21:34:52
【问题描述】:
我的 web 应用程序将 Laravel 作为后端框架,它提供了一个 Restful API,并且在前端运行了 Angularjs。 我通过 api 发送不同的请求并接收响应,并根据响应代码和包含的数据,向用户显示适当的消息。
最近,当我使用 PUT 方法或 POST 方法发送请求时,当数据在验证过程中出现问题并且 Laravel 应该以 JSON 格式的 422 代码响应时,我收到了带有代码 200 的 text/html 响应。然后一切出错了。
这不会发生在我的本地机器上,只有当我在生产环境中测试应用程序时才会发生这种情况。
我还测试了使用 403 代码发送的 UnAuthorized 响应,它运行良好。
我测试了 Laravel 的自动验证错误(如文档中所述:在 AJAX 请求期间使用 validate 方法时,Laravel 不会生成重定向响应。相反,Laravel 会生成包含所有验证错误的 JSON 响应。此 JSON 响应将使用 422 HTTP 状态代码发送。)并且还使用以下方法:
return response()->json(compact('errors'),422);
我应该提到我使用以下方法发送 AJAX 请求:
function save(data, url) {
return $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/json'},
data: angular.toJson(data)
});
}
function update(data, url) {
return $http({
method: 'PUT',
url: url + data.id,
headers: {'Content-Type': 'application/json'},
data: angular.toJson(data)
});
}
不用说我完全糊涂了!
更新:这似乎是 Laravel 验证过程的问题。当验证运行时,请求变得错误。请看以下代码:
public function altUpdate(Request $request){
$this->authorize('editCustomer', $this->store);
if (!$request->has('customer')){
return response()->json(["message"=>"Problem in received data"],422);
}
$id = $request->customer['id'];
$rules = [
'name' => 'required',
'mobile' => "required|digits:11|unique:customers,mobile,$id,id,store_id,$this->store_id",
'phone' => 'digits_between:8,11',
'email' => "email|max:255|unique:customers,email,$id,id,store_id,$this->store_id",
];
//return response()->json(["problem in data"],422); //this one works properly if uncommented
$validator = Validator::make($request->customer,$rules);
if ($validator->fails()){
$errors = $validator->errors()->all();
Log::info($errors);
return response()->json(["problem in data"],422);//this one is received in client side as a text/html response with code 200
}
$customer = Customer::find($id);
$customer->update(wrapInputs($request->all()));
if ($request->tags) {
$this->syncTags($request->tags, $customer);
}
$message = "Customer updated successfully!";
return response()->json(compact('message'));
}
我仍然不知道验证过程有什么问题。此代码在我的本地机器上运行没有任何问题,但在生产服务器上出现问题。
【问题讨论】:
-
错误日志中有什么内容吗?通常一个 200 可能发生在一个失败但没有抛出正确错误代码的请求中。最好将 http_response_code(500) 设置为响应代码中的第一行,这样它将默认为 500 而不是 200。
-
不,日志中没有任何内容。我应该在哪里使用 set_http_response(500)?验证前? @shylor
标签: php angularjs json ajax laravel-5.2