我的web应用使用Laravel作为后端框架,它提供Restful API,而在前端运行Angularjs。我通过api发送不同的请求并接收响应,并根据响应的代码和包含的数据,向用户显示适当的消息。
最近,当我使用PUT方法或POST方法发送请求时,当数据在验证过程中有问题时,Laravel应该以JSON格式响应422代码,而不是收到代码为200的文本/html响应。然后一切都出了问题。
这不会发生在我的本地机器上,只有当我在生产环境中测试应用程序时才会发生。
我还测试了未经授权的响应,它是用403代码发送的,它工作得很完美。
我测试了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)
});
}
不用说,我完全糊涂了!
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'));
}
我还是不知道验证过程有什么问题。这段代码在我的本地机器上运行没有任何问题,但是在生产服务器上出现了问题。
我终于明白了。我添加了一个语言文件,该文件是用UTF-8-BOM编码的,当我将该文件转换为没有BOM的UTF-8时,事情就变得正确了。
文件是resources/lang/[the language]/validate .php,由于编码问题,在处理该文件时发送了头文件。
这个问题也帮助我找到了问题:Laravel redirect::route在页面加载之间显示消息