我的webapp將Laravel作爲後端框架,它提供了一個Restful API並且在Angularjs正在運行。 我通過API發送不同的請求並接收響應,並根據響應代碼和包含的數據向用戶顯示適當的消息。Laravel與Angularjs驗證json請求不良響應
最近,當我使用PUT方法或POST方法發送請求時,當數據在驗證過程中出現問題並且Laravel應該以JSON格式響應422代碼時,我接收到代碼爲200的text/html響應。一切都出錯了。
這不會發生在我的本地機器上,只有當我在生產環境中測試應用程序時,纔會發生這種情況。
我還測試了與403代碼一起發送的未經授權的響應,它的工作原理完美無瑕。我測試了Laravel的自動驗證錯誤(如文檔中所述:在AJAX請求期間使用validate方法時,Laravel不會生成重定向響應,相反,Laravel生成一個包含所有驗證錯誤的JSON響應。
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)
});
}
這JSON響應將有422 HTTP狀態代碼,使用下面的方法來發送)和也。不用說我變得完全困惑!
UPDATE:這似乎是與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. – Shylor
不,日誌中沒有任何內容。我應該在哪裏使用set_http_response(500)?驗證之前? @shylor – rastemoh