Guilherme Ramalho
Guilherme Ramalho

Reputation: 186

Httpful: Unable to parse response as JSON

I'm developing an web app using CodeIgniter and requesting data from a Slim REST Api. I'm having problems on my web app to get a response from a Httpful request. I use a base function to make all requests on my CodeIgniter frontend app, It goes like this:

function httpRequest($verb, $endpoint, $sentHeaders = null, $body = null)
{
    try {
        require FCPATH . 'vendor/autoload.php';

        $context = & get_instance();

        $xUsuario = $context->session->usuario;

        $headers = array(
            'Content-Type' => 'application/json',
            'xAuthChaveApi' => $context->session->userdata('CLIENT_KEY'),
            'xAuthUsuarioID' => $xUsuario['id'],
            'xAuthUsuarioToken' => $xUsuario['sessao']['token']
        );

        if (isset($sentHeaders)) {
            $headers = array_merge($headers, $sentHeaders);
        }

        /*=========THE EXCEPTION IS THROWN HERE=========*/
        $response = \Httpful\Request::{$verb}(API_URL . $endpoint)
            ->addHeaders($headers)
            ->body(json_encode($body))
            ->send();

        if ($response->code == 401) {
            encerrarSessao('Usuário não autorizado! Verifique os dados das suas credenciais e tente novamente');
        }

        return json_decode(json_encode($response->body), true);
    } catch (Exception $ex) {
        show_error('O seguinte erro ocorreu ao fazer requisição aos servidores: ' . $ex->getMessage());
    }
}

I've tested with both the Web App and the API hosted on my localhost, the App on my localhost and the API on the Hostgator's server and It works like a charm. But when both the App and the Api are hosted on the online server is when I get the error. Funny thing is that the error only occurs on this particular endpoint, I have no problems at all with the others either local or online. I can even call this endpoint on the server with postman and It works fine.

This is the endpoint code I have on the API:

public static function listarImportacao(Request $request, Response $response) {
        try {
            $dataInicial = $request->getHeader('dataInicial')[0];
            $dataFinal = $request->getHeader('dataFinal')[0];

            if(!isset($dataInicial) && !isset($dataFinal)) {
                $dataInicial = date('Y-m-d');
                $dataFinal = date('Y-m-d', strtotime('+1 day'));
            }

            $partidas = Partida::whereBetween(
                'dataHora',
                array($dataInicial, $dataFinal)
            )
            ->with(array('liga.pais', 'timeCasa', 'timeFora'))
            ->where('flagDisponivel', '!=', '1')
            ->where('cotacao', '!=', 'null')
            ->whereRaw('(dataHora >= (now() + INTERVAL 5 MINUTE))')
            ->get();

            $meta = Helper::metaArray(Enum::SUCS_STS, Enum::SELECTED);

            $partidas = Helper::formatarPartidas($partidas);

            return $response->withCustomJson($meta, $partidas);

        } catch (Exception $ex) {
            $meta = Helper::metaArray(Enum::ERR_STS, $ex, 400);

            return $response->withCustomJson($meta);
        }
    }

This is the controller function that makes the request:

public function importacao() {
        try {
            $post = $this->input->post();

            if(isset($post['dataInicial']) && isset($post['dataFinal'])) {
                $dataInicial = dataAmericana($post['dataInicial']);
                $dataFinal = dataAmericana($post['dataFinal']);

                setFlashData($post['dataInicial'], 'dataInicial');
                setFlashData($post['dataFinal'], 'dataFinal');
            } else {
                $dataInicial = date('Y-m-d', strtotime('today'));
                $dataFinal = date('Y-m-d', strtotime('+1 day'));
            }

            $headers = array(
                'dataInicial' => $dataInicial,
                'dataFinal' => $dataFinal
            );

            $partidas = httpRequest('GET', Endpoint::listaImportacao, $headers);

            //var_dump($partidas['data']); die();

            $dados = array(
                'titulo' => 'Importação de Partidas',
                'nomeView' => 'partida/importacao',
                'partidas' => isset($partidas['data']) ? $partidas['data'] : null
            );

            $this->load->view('menus/main', $dados);
        } catch (Exception $ex) {
            show_error('O seguinte erro ocorreu ao fazer requisição aos servidores: ' . $ex->getMessage());
        }
    }

Is there anything I'm missing here? Thanks in advance.

Upvotes: 3

Views: 4062

Answers (1)

Aren
Aren

Reputation: 221

I had this error also Unable to parse response as JSON and I was sure the returned json was ok. After a long search there was also a php error in the output for a missing variable. That was corrupting the correct json output. So check for php related errors.

Upvotes: 1

Related Questions