Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - HTTP 200 treated as error

I am trying to get Angular2 to work with my Asp.Net WebApi 2 server. I managed to handle some GET requests correctly, however this POST request behaves strangely. I receive an OK (200) response from my server, yet the following code treats it as an error:

public Register(){
    this.accountService.Register(this.Name, this.Password, this.RepeatPassword, this.Email, this.Skype, this.Website).subscribe(
        () => {      //this is what's supposed to be called, but isn't
            this.accountService.Login(this.Name, this.Password).subscribe(
                res => {
                    console.log(res);
                    localStorage.setItem('token', res);
                    localStorage.setItem('user', this.Name);
                    this.router.navigate(['Home']);
                },
                error2 => {
                    console.log(error2.Message);
                }
            );
        },
        error => { //the response gets here, instead of being handled above
            console.log(error.Message);
        }
    );
}

Here is the Register method of the accountService:

public Register (userName:string, password:string, confirmPassword:string, email:string, skype:string, website:string)
{
    return this.http.post(this.Uri + 'api/Account/Register', JSON.stringify(
        {
            UserName: userName,
            Password: password,
            ConfirmPassword: confirmPassword,
            Email: email,
            Skype: skype,
            Website: website
        }), this.GetRequestOptions() ).map((res: Response) => res.json());
}
like image 649
Noctiphobia Avatar asked Jan 17 '16 20:01

Noctiphobia


2 Answers

Finally found the answer. Ajax, when it's expecting a json, fires off the error callback after getting HTTP 200 with a malformed json (including an empty file). The fix was to replace all empty responses with {}.

To do this in a ASP.Net WebApi2 server, you need to use return Ok("{}"); instead of just return Ok(); at the end of the method being called.

An alternative solution (and most likely a better one) is to change the calling code - in particular, .map((res: Response) => res.json()) is the bit of code that failed - a conditional checking if res is empty could be added before calling res.json().

like image 107
Noctiphobia Avatar answered Nov 16 '22 03:11

Noctiphobia


I was having the same problem here. But in my case it was that I forgot to tell Angular which kind of response my endpoint was sending. For more information you can read the GreyBeardedGeek response at stackoverflow.

like image 2
Filipe Luchini Avatar answered Nov 16 '22 04:11

Filipe Luchini