Angular2 - HTTP 200 被视为错误

Angular2 - HTTP 200 treated as error

我正在尝试让 Angular2 与我的 Asp.Net WebApi 2 服务器一起工作。我设法正确处理了一些 GET 请求,但是这个 POST 请求的行为很奇怪。我从服务器收到 OK (200) 响应,但以下代码将其视为错误:

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);
        }
    );
}

这里是accountService的Register方法:

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());
}

终于找到答案了。 Ajax,当它期待 json 时,在收到格式错误的 json(包括一个空文件)的 HTTP 200 后触发错误回调。解决方法是用 {} 替换所有空响应。

要在 ASP.Net WebApi2 服务器中执行此操作,您需要在调用方法的末尾使用 return Ok("{}"); 而不是仅 return Ok();

另一种解决方案(很可能是更好的解决方案)是更改调用代码 - 特别是,.map((res: Response) => res.json()) 是失败的代码位 - 有条件地检查 res 是否为空可以在调用 res.json().

之前添加

我在这里遇到了同样的问题。但就我而言,是我忘记告诉 Angular 我的端点正在发送哪种响应。有关详细信息,您可以阅读 .