在Laravel中的休息调用中返回错误消息

时间:2017-10-15 12:42:00

标签: php laravel rest laravel-5 http-post

我必须在laravel 5中收到客户端发送到我的REST应用程序的POST请求。我按照与验证相关的文档,它说当AJAX请求laravel何时不生成重定向响应,而是它将生成一个带有错误的JSON响应(https://laravel.com/docs/5.5/validation#a-note-on-optional-fields)。但是当我从REST客户端拨打电话时,我得到了这个回复:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url=http://laraveltest.com:8080/test/public" />

        <title>Redirecting to http://laraveltest.com:8080/test/public</title>
    </head>
    <body>
        Redirecting to <a href="http://laraveltest.com:8080/test/public">http://laraveltest.com:8080/test/public</a>.
    </body>
</html>

AdultoPost班级*********************

class AdultoPost extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'Profesion' => "max:50",
            "EstadoCivil" => "required",
            "FamiliaReconstituida" => "required",
            "SolteroConHijo" => "required",
            "Viudo" => "required",
            "NoHijos" => "required"
        ];
    }
}

AdultoController **************

 public function post(AdultoPost $request, Adulto $adulto, Paciente $paciente, Persona $persona)
        {
            $persona = Persona::create($request->all());
            $adulto = Adulto::create($request->all());
            $paciente = Paciente::create($request->all());
return $adulto;
    }

如果我为Request更改了AdultoPost类并将验证规则放在post函数中并捕获ValidationException,我会收到此错误响应&#34;给定的数据无效&#34;。这不是我想要的。我想向客户发送哪些字段无效以及原因。

我是从VSCODE的REST API插件发出请求,也是从chrome的REST API TESTING扩展中发出请求,现在我正在安装POSTMAN以继续测试

POST http://laraveltest.com:8080/test/public/api/adulto
Content-Type: application/json
Accept: application/json

{
    "FechaInicio":"2017-09-10",
    "MotivoConsulta":"un motivo real",
    "ComoConocio":"como conocio"
}

1 个答案:

答案 0 :(得分:1)

您如何向客户提出请求。请务必设置正确的标头,这是一个有效的JSON请求:

Content-Type: application/json
Accept: application/json

卷曲示例:

curl -H "Content-Type: application/json" -H "Accept: application/json"  -X POST -d '{"username":"xyz","password":"xyz"}' http://localhost/api