Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $http always returning null data from PHP API

Tags:

php

angularjs

I am trying to use a login API that one of my developers created for me.

$http({
    method: 'POST',
    url: "http://example.com/api/userLogin",
    data: $.param(postLoginData),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    responseType: 'json'
}).then(function(loginData) {
    console.log(loginData);
});

My console.log() always logs the following:

Object {data: null, status: 200, config: Object, statusText: "OK"}

Yet when I go to the Network tab within developer tools, I can see that the response is actually the following:

enter image description here

I'm not a backend developer, so I was a little confused with this 0 at the beginning of the response. I then tried to investigate this further and looked into the PHP API code itself, and found that the response from curl_exec($loginCurl) that is returned is:

HTTP/1.1 100 Continue

HTTP/1.1 200 OK
Date: Mon, 09 May 2016 02:10:35 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.14
Cache-Control: no-cache
Content-Length: 43
Content-Type: application/json

{"id":"16","username":"user4","status":200}

The body of the response is valid JSON, so not too sure why Angular is returning null data, even though I can see the response in developer tools successfully...


EDIT:

My API contained the following to perform checks and create sessions:

$jsonResults = json_decode($body, true);
if($jsonResults != NULL || $jsonResults->id != NULL) {
    //Successfully logged in
    $_SESSION['user_name'] = $jsonResults->username;
    $_SESSION['user_login_status'] = 1;
    $_SESSION['user_id'] = $jsonResults->id;

    $this->response($body, 200);
}

Although, if the entire above code is just replaced with the following, it seems to work perfectly fine:

$this->response($body, 200);

Why would this be?

like image 797
Fizzix Avatar asked Feb 11 '26 09:02

Fizzix


1 Answers

The problem is definitely server-side however you can work around it using a response transformer. For example...

$http.post('http://example.com/api/userLogin', $.param(postLoginData), {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    transformResponse: function(data) {
        console.log('Raw data', data);
        if (angular.isString(data) && data[0] === '0') {
            data = data.substring(1);
        }
        return angular.fromJson(data);
    }
}).then(function(response) {
    console.log(response);
})
like image 103
Phil Avatar answered Feb 14 '26 15:02

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!