1

Could anyone tell me why the following statement does not send the post data to the designated URL?

login: function (username, password) {
    var deferred = $q.defer();

    var url = Config.serverUrl() + "/api-token-auth/";
    var data = {
        'username': username,
        'password': password
    };

    $http.post(url, data).then(function (responseData) {
        console.log(responseData);
        alert(url);
        alert(JSON.stringify(data));
        $localForage.setItem('shopper-user', responseData.data).then(function (user) {

            var token = "JWT " + user.token;
            $rootScope.token = token;
            $http.defaults.headers.common.Authorization = $rootScope.token;

            deferred.resolve(user);
        });

    }, function (error) {
        alert(url);
        alert(JSON.stringify(data));
        console.error(error);
        alert(JSON.stringify(error));
        deferred.reject(error);
    });

    return deferred.promise;
}

The URL is called on the server, but only go to the error state

Error:

{"data":null, "status":-1,"config":{"method":"POST"}}
Community
  • 1
  • 1
Mishu Lojan
  • 129
  • 3
  • 11
  • what is your response code? 500? – Junbang Huang Apr 06 '17 at 21:52
  • Your server is not responding/request is timing out, try to [ping](https://iihelp.iinet.net.au/How_to_run_a_ping_test) the server and see what you get back – cnorthfield Apr 06 '17 at 22:04
  • Possible duplicate of [Angular $http status (-1)](http://stackoverflow.com/questions/33483220/angular-http-status-1) (not adding the close vote yet, will wait for feedback from OP) – Phil Apr 06 '17 at 23:11
  • The most common cause of status -1 is a [Same Origin Policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) violation. Modify the server to use [CORS](https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS) to allow cross-origin access. – georgeawg Apr 06 '17 at 23:45
  • Also there is no need to manufacture a promise with `$defer` as the `$http` service already returns a promise. See [Is this a “Deferred Antipattern”?](http://stackoverflow.com/questions/30750207/is-this-a-deferred-antipattern). – georgeawg Apr 06 '17 at 23:53

1 Answers1

1

Client side code seems OK.

It's probably a CORS issue. Pleasure ensure server-side code responds 200 to OPTIONS request (made by Angular before POST request) and that response headers are properly set.

You can find more information on how to configure CORS here

Stephane Janicaud
  • 3,531
  • 1
  • 12
  • 18