Angular2 - HTTP 200被视为错误

Noc*_*bia 6 ajax http response angularjs asp.net-web-api2

我想让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);
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

这是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());
}
Run Code Online (Sandbox Code Playgroud)

Noc*_*bia 10

终于找到了答案.Ajax,当它期待一个json时,在获取带有格式错误的json(包括空文件)的HTTP 200之后触发错误回调.修复是用{}替换所有空响应.

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

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

  • 你能在代码中展示你的修复吗?也遇到类似的问题. (2认同)