2

I'm attempting to call an endpoint on my api, how every call I make goes to the error callback on the promise rather than the success callback, even if the request actually is a success (Returning 200 and valid json).

I'm using ngResource to make the call.

Resource:

angular.module("ya").factory("Account", [
    "$resource", function ($resource) {
        return $resource(apiUrl, {}, {
            "register": {
                method: "POST",
                params: {},
                url: apiUrl + "api/Account/Register"
            },
            "login": {
                method: "POST",
                params: {},
                url: apiUrl + "token",
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
            }
        });
    }

In controller:

var creds = {
    email: register.email,
    password: register.password,
    confirmPassword: register.password
}
var r = Account.register(creds);
console.log(r);
r.$promise.then(function(result) {
    console.log(result);
}, function(result) {
    console.log("error");
    console.log(result);
});

console.log(r) gives:

{
    "email": "bla6@bla.bla",
    "password": "password",
    "confirmPassword": "password"
}

as expected.

Next the console logs "error", so i know it's in the error callback. The next object that is logged is this:

{
    "data": null,
    "status": -1,
    "config": {
        "method": "POST",
        "transformRequest": [null],
        "transformResponse": [null],
        "url": "http://localhost:57053/api/Account/Register",
        "data": {
            "email": "bla6@bla.bla",
            "password": "password",
            "confirmPassword": "password"
        },
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8"
        }
    },
    "statusText": ""
}

Which doesn't really tell me anything about what went wrong.

Looking at the request in the network inspector in firefox tells me the error got a 200 response and returned the following json:

{
    "message": "User was registered successfully"
}

I'm not quite sure else could go wrong.

This is my config if it's any help:

angular.module("ya", ["ngMaterial", "ui.router", "ngResource"])
    .config(["$mdThemingProvider", "$stateProvider", "$urlRouterProvider", "$locationProvider", "$sceDelegateProvider", 
    function ($mdThemingProvider, $stateProvider, $urlRouterProvider, $locationProvider, $sceDelegateProvider) {

        // Set application theme
        $mdThemingProvider.theme("default").dark();

        // Enable html5 mode
        $locationProvider.html5Mode(true);

        // Set default page
        $urlRouterProvider.otherwise("home");

        $stateProvider.state("home", {
            url: "/home",
            templateUrl: "templates/home.html",
            controller: "homeController", 
            controllerAs: "home"
        }).state("auth", {
            url: "/auth",
            templateUrl: "templates/authentication.html",
            controller: "authController",
            controllerAs: "auth"
        });

        $sceDelegateProvider.resourceUrlWhitelist(["self", "http://*.zlepper.dk/**", "http://localhost:*/**"]);
    }]);

And the request goes to: http://localhost:57053/api/Account/Register as intended.

EDIT a bit more testing shows the same issue happens when using jQuery.post.

It's not any more descriptive on the error.

The code that runs on the api if it's any help.

    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        return Ok(new Dictionary<string, string>() {{"message", "User was registered successfully"}});
    }

EDIT 2 This is the headers the call have.

Request headers:

Host: localhost:57053
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://localhost:3000/auth
Content-Type: application/json;charset=utf-8
Content-Length: 76
Origin: http://localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Response headers:

Cache-Control: no-cache
Content-Length: 53
Content-Type: application/json; charset=utf-8
Date: Wed, 30 Dec 2015 21:15:28 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcUmFzbXVzXERvY3VtZW50c1xHaXRIdWJcY3VybHktZ2FyYmFuem9cY3VybHktZ2FyYmFuem9cYXBpXEFjY291bnRcUmVnaXN0ZXI=?=
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:3000, *

OPTIONS request:

OPTIONS /api/Account/Register HTTP/1.1
Host: localhost:57053
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

OPTIONS response:

HTTP/1.1 200 OK
Server: Microsoft-IIS/10.0
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcUmFzbXVzXERvY3VtZW50c1xHaXRIdWJcY3VybHktZ2FyYmFuem9cY3VybHktZ2FyYmFuem9cYXBpXEFjY291bnRcUmVnaXN0ZXI=?=
X-Powered-By: ASP.NET
Date: Thu, 31 Dec 2015 10:29:07 GMT
Content-Length: 0
Rasmus Hansen
  • 1,502
  • 1
  • 17
  • 28
  • It looks like you are actually logging messages in both success and error functions which could get confusing if you are debugging. Are you sure that is calling the error and not the success callback? – segFault Dec 30 '15 at 20:05
  • Yup, but the success callback doesn't happen, as a message is never logged from there (looking at the line numbers the logging occured from). Also considering the time the call takes it logs a response way to fast, before the request is even processed on the server. – Rasmus Hansen Dec 30 '15 at 20:10
  • Are you using interceptors? https://docs.angularjs.org/api/ng/service/$http#interceptors – Danny Dec 30 '15 at 20:15
  • Also you could consider taking a look at [this similar question](http://stackoverflow.com/questions/20584367/how-to-handle-resource-service-errors-in-angularjs) – segFault Dec 30 '15 at 20:17
  • @Dan I don't think so. – Rasmus Hansen Dec 30 '15 at 20:17
  • @sebastianForsberg I do know how to handle errors. My problem is that the error happens in the first place, when it should be a success according to everything i know. It's the same issue if I do it using only $http to make the request. – Rasmus Hansen Dec 30 '15 at 20:20
  • Not sure what is going on, but I setup a test plunker [here](http://plnkr.co/edit/6yOdXxIrwbilEgI5bayx?p=preview) Obviously it doesn't use your API, but it is able to send a POST to a faux API and it hits the success callback as it should. I think there is something up with the server side of things, maybe it is not sending all of the expected headers? – segFault Dec 30 '15 at 20:49
  • I added the headers to the OP, if they are any help. – Rasmus Hansen Dec 30 '15 at 21:17
  • When you check the network tab in Firefox console after initiating the register call, does it show an `OPTIONS` request made to `http://localhost:57053/api/Account/Register`? Rather than a `POST`? – segFault Dec 30 '15 at 21:40
  • You are getting a status of -1. That means either a timeout or an abort in `$httpBackend` – georgeawg Dec 30 '15 at 23:32
  • @sebastianForsberg It doesn't show the option request in firefox, but using fiddler i can see an option request is send. I will add the request to the op. – Rasmus Hansen Dec 31 '15 at 10:30
  • @georgeawg And what would cause that to happen? – Rasmus Hansen Dec 31 '15 at 10:52
  • Maybe the default response transformer is throwing an error. Try setting `transformResponse: [],` Setting it to an empty array will bypass any response transform. You can then look at the raw data. – georgeawg Dec 31 '15 at 17:48
  • @georgeawg Sadly didn't help at all. Same result. As i mentioned earlier, it errors before the server even responds, so I doubt that's the issue anyway. – Rasmus Hansen Dec 31 '15 at 19:46

0 Answers0