2017-10-15 55 views
0

我必须从客户端收到一个POST请求到laravel 5中的REST应用程序。我按照有关验证的文档,它表示,当一个AJAX请求laravel不生成重定向响应,而不是生成一个带有错误的JSON响应(https://laravel.com/docs/5.5/validation#a-note-on-optional-fields)。但是,当我提出从REST客户端我得到这个响应召唤:在Laravel返回其他电话的错误消息

<!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; 
    } 

如果我改变AdultoPost类请求,并把验证规则后函数内,赶上一个ValidationException我得到这个错误回应“给定的数据无效”。这不是我想要的。我想向客户发送哪些字段无效以及为什么。

我正在从VSCODE的REST API插件的请求,并从REST API测试扩展由铬,现在我安装邮递员继续测试

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" 
} 
+0

请注明你如何要求你的REST API。如果你正在做Ajax,你可以在控制台上查看你的api发送的实际数据结构,但是如果你没有使用ajax,那么请在你的html表单和处理你的请求的实际功能代码上提供你的代码。 – dexterb

回答

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 
+0

已添加Accept:application/json,但仍然遇到同样的问题 –

+1

在您更新的问题中,我只能看到'Content-type'。我刚刚测试了我的api端点,它只需要'Accept:application/json'。 “Content-type”不起作用。 – Bostjan

+0

太好了,非常感谢,我疯了。我必须删除内容类型!然后添加Accept:application/json,因为两者同时不工作! –