使用Angularjs的Laravel验证json请求错误响应

时间:2016-11-15 20:46:43

标签: php angularjs json ajax laravel-5.2

我的webapp有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'));
}

我仍然不知道验证过程的问题是什么。此代码正在我的本地计算机上工作没有任何问题,但在生产服务器上出现问题。

1 个答案:

答案 0 :(得分:3)

我终于明白了。 我添加了一个语言文件,文件以UTF-8-BOM编码,当我将该文件转换为UTF-8而没有BOM时,事情变得正确。

该文件是resources / lang / [语言] /validation.php,并且由于编码问题,在处理此文件时正在发送标头。

这个问题也帮我找到了问题: Laravel redirect::route is showing a message between page loads

相关问题