【问题标题】:Angular2 - HTTP 200 treated as errorAngular2 - HTTP 200 被视为错误
【发布时间】:2016-04-22 22:36:51
【问题描述】:

我正在尝试让 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());
}

【问题讨论】:

    标签: angularjs ajax http asp.net-web-api2 response


    【解决方案1】:

    我在这里遇到了同样的问题。但在我的情况下,我忘记告诉 Angular 我的端点正在发送哪种响应。更多信息可以阅读the GreyBeardedGeek response at stackoverflow

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 你能在代码中显示你的修复吗?也遇到类似的问题。
      • 它就像一个魅力。我的 API 端点只返回一个字符串,而默认情况下,Angular 的 post 方法响应应该是“JSON”。将响应类型更改为“文本”,最后,它可以正常工作。谢谢。
      猜你喜欢
      • 2014-07-04
      • 2016-03-31
      • 2019-06-10
      • 2016-11-14
      • 2016-12-23
      • 2017-05-23
      • 2015-06-12
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多