簡體   English   中英

Angular 6 HTTP 處理成功響應(成功代碼:200)作為錯誤響應

[英]Angular 6 HTTP deals with successful Response (Sucess Code: 200) as error response

同樣的代碼在 Angular 2 上工作,但在 Angular 6 上它在 http 上返回錯誤(即 http 錯誤處理程序失敗)但請求成功(代碼:200 並按預期返回數據)

更新問題摘要基本上是cors問題

1-我使用的是 Angular2 HTTP 而不是自 Angular4 以來應用的 HttpClient

2- 雖然這不是主要問題,但我在 chrome 上顯示了 CORS 錯誤(可能在使用 httpclient 之后)

3-不需要添加responsType,在解決服務器端的cors錯誤后它就可以工作了。

舊的錯誤代碼:

var headers = new Headers();
  headers.append("Accept", 'application/json');
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  let options = new RequestOptions({ headers: headers });

  let postParams = "grant_type=password&username="+username+"&password="+password;
  this.http.post("api/Token", postParams, options)
      .subscribe(data => {
               console.log(data);
       },  
      error => {
        //can I get the response body here?
        console.log(JSON.stringify(error));

相關問題在此鏈接https://github.com/angular/angular/issues/19555上找到,所以我嘗試添加 responseType,如下

另外根據這個問題,我試圖傳遞 responseType 屬性,但它也不起作用Angular 6: How to set response type as text while making http call

      this.http.post(AppSettings.apiaddress + "Token", postParams, {headers,responseType: ResponseContentType.Text})

如果沒有辦法讓它工作,有沒有辦法在錯誤處理程序上獲取數據作為解決方法?

感謝您的幫助,但如果您不知道答案,則無需投票,因此其他人可以提供幫助,謝謝

請嘗試這種方式。

var headers = new Headers();
  headers.append("Accept", 'application/json');
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  let postParams = "grant_type=password&username="+username+"&password="+password;
  this.http.post("api/Token", postParams, {headers, 'responseType': 'json'})
      .subscribe(data => {
               console.log(data);
       },  
      error => {
        //can I get the response body here?
        console.log(JSON.stringify(error));

並嘗試替換為var headers = new Headers(); var headers = new HttpHeaders();

暫無
暫無

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

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