API Slim returns error only with AJAX request

1
Hello, I developed an API using the Slim Framework and testing one of the endpoints that with Postman works perfectly but when I do the AJAX request, although it is sending exactly the same data that I send with postman, it seems that the data does not arrive correctly and I do not know why.

Request on Postman:

AJAXFunction:

functionajaxRequest(verb,endpoint,headers=null,body=null){try{//Animaçãodoloading$('.container').waitMe({effect:'facebook'});varresp=null;$.ajax({url:'http://localhost/projetos/soccerama/api/'+endpoint,type:verb,ContentType:'application/json',async:false,headers:{'xAuthChaveApi':localStorage.xAuthChaveApi,'xAuthCambistaID':localStorage.xAuthCambistaID,'xAuthCambistaToken':localStorage.xAuthCambistaToken},success:function(response){resp=response},error:function(error){notificar(Status.SERVER_ERR);},beforeSend:function(xhr){if(headers!==null){for(varkeyinheaders){xhr.setRequestHeader(key,headers[key]);}}}});}catch(error){notificar(error);}finally{$('.container').waitMe('hide');returnresp;}}

Calltheajaxfunctionintheauthenticationfunction:

functionautenticar(){varusuario=$('#inputUsuario').val();varsenha=$('#inputSenha').val();varpin=$('#inputPin').val();if(!usuario||!senha||!pin){notificar('Ops!Temalgoerrado,temcertezaquedigitouoseuusuário,senhaePINcorretamente?');returnnull;}//Declarandoosheadersvarheaders={usuario:usuario,senha:senha,}varcambista=ajaxRequest(Verb.GET,Endpoint.AUTH_CAMBISTA,headers);}

Requestdatacollectedfromthebrowser:

RequestURL:http://localhost/projetos/soccerama/api/cambista/autenticarRequestMethod:GETStatusCode:200OKRemoteAddress:[::1]:80ReferrerPolicy:no-referrer-when-downgradeResponseHeadersviewsourceConnection:Keep-AliveContent-Length:315Content-Type:application/json;charset=utf-8Date:Fri,03Nov201716:04:59GMTKeep-Alive:timeout=5,max=100Server:Apache/2.4.28(Unix)OpenSSL/1.0.2lPHP/7.1.10mod_perl/2.0.8-devPerl/v5.16.3X-Powered-By:PHP/7.1.10RequestHeadersviewsourceAccept:*/*Accept-Encoding:gzip,deflate,brAccept-Language:pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7Connection:keep-aliveHost:localhostReferer:http://localhost/projetos/soccerama/mobile/www/login.htmlsenha:testeUser-Agent:Mozilla/5.0(X11;Linuxx86_64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/62.0.3202.75Safari/537.36usuario:adminX-Requested-With:XMLHttpRequestxAuthChaveApi:3851b1ae73ca0ca6e3c24a0256a80ace

Browserresponse:

{"meta":{
      "status":"warning",
      "message":"Um erro ocorreu ao executar a opera\u00e7\u00e3o. Tente 
      novamente ou entre em contato com o administrador."
   }
}
Notice:  Undefined variable: cambista in /opt/lampp/htdocs/projetos/soccerama/api/app/controllers/CambistaController.php on line 168

API Method:

public static function autenticar(Request $request, Response $response) {
        try {
            $credenciais = array(
                'login' => (array_key_exists(0, $request->getHeader('login')) ? $request->getHeader('login')[0] : null),
                'senha' => (array_key_exists(0, $request->getHeader('senha')) ? md5(SALT . $request->getHeader('senha')[0]) : null)
            );

            if ( isset($credenciais['login']) && isset($credenciais['senha']) ) {
                $cambista = Cambista::where($credenciais)
                    ->get()
                    ->first();

                if (isset($cambista)) {
                    $cambista->sessao = new Sessao();
                    $cambista->sessao->idCambista = $cambista->id;
                    $cambista->sessao->token = md5(uniqid(rand(), true));
                    $cambista->sessao->save();

                    $cambista = cambista::where('id', $cambista->id)
                        ->with('telefones')
                        ->with('regional')
                        ->with([
                            'sessao' => function($query) {
                                $query->orderBy('criado', 'DESC')->take(1);
                            }
                        ])
                        ->get()
                        ->first();

                    $meta = Helper::metaArray(Enum::SUCS_STS, Enum::AUTHORIZED);
                } else {
                    $meta = Helper::metaArray(Enum::WARN_STS, Enum::LOGIN_ERROR);
                }
            } else {
                $meta = Helper::metaArray(Enum::WARN_STS, Enum::INTERNAL_ERROR);
            }

            return $response->withCustomJson($meta, $cambista);
        } catch (Exception $ex) {
            $meta = Helper::metaArray(Enum::ERR_STS, Helper::exceptionError($ex), 400);

            return $response->withCustomJson($meta);
        }
    }
    
asked by anonymous 03.11.2017 / 17:23

0 answers