簡體   English   中英

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 我的端點正在發送哪種響應。 有關更多信息,您可以閱讀stackoverflow 上的 GreyBeardedGeek 響應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM