2017-10-15 3 views
0

Angular 4Http 요청이 있습니다. 내장 된 HttpClient 클래스를 사용하고 있습니다. 모든 것이 잘 작동하지만 반환 된 오류 변수에는 작은 문제가 있습니다. 나는 사용자가 로그인 할 때 잘못된 사용자 이름/암호 조합을 post 때 오류 개체가 반환Angular4 - 반환 된 HTTP 오류가 객체가 아닌 문자열입니다.

는 가치가 Object 것으로 예상되는 대한 error 키를 포함하지만 대신 string을 얻고있다.

{**error: "{"non_field_errors":["Unable to login with provided credentials."]}"**, headers: Object, status: 400, statusText: "Bad Request", url: "http://mymedicine.loc/api/auth/login/", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://project.loc/api/auth/login/: 400 Bad Request"} 

어떻게 이런 종류의 문제가 발생할 수 있습니다 : 문제의 이해하는 객체에 ** 사이에있는 텍스트 아래 참조하십시오? 거기에 객체가 있어야만 인증 중에 무엇이 잘못되었는지 알 수 있습니다. 정확한 자격 증명이 제공되고 웹 서버에 CORS을 활성화 시켰을 때 나는 HTTP 요청을 보내고 있습니다. 다음은

POST HTTP 요청을 수행 추출 코드의 짧은 조각이다 :

interface ErrorMessage { 
    username: string[1]; 
    password: string[1]; 
    non_field_errors: string[1]; 
} 

interface ErrorResponse { 
    error: ErrorMessage; 
} 

// get token from the server 
this.http.post<TokenResponse>('http://myproject.loc/api/auth/login/', body).subscribe(
    (res: TokenResponse) => { 
     // login with token 
     this.auth.login(res.auth_token); 

     // redirect 
     this.router.navigateByUrl('/url'); 
    }, 
    (err: ErrorResponse) => { 
     let error = err.error; 
     console.dir(err); 
    } 
); 
+0

오류 개체의 json은 개체가 아닌 문자열로 서식이 지정됩니다. 서버를 제어합니까? 그렇다면 오류 개체 주변의 따옴표를 제거하여 문제를 해결하십시오. 그렇지 않은 경우 JSON.parse를 사용하여 응답을 구문 분석하십시오. – bryan60

+2

https://github.com/angular/angular/issues/18682 – jonrsharpe

+0

@ bryan60 예 서버에서 반환 한 데이터를 제어 할 수 있지만 'curl'이 응답을 반환하므로 문제가 발생하지 않는다고 생각합니다. 명령 줄에서 괜찮 으면 (즉, json 객체) – h4k1m

답변

0

에 대한 게시물 요청의 헤더에 JSON으로 콘텐츠 유형을 설정하십시오 이 오류는 최근 버전의 AngularAngular-cli에 따라 source에 따라 수정 된 것으로 보이며 Angular 4.4.6이 아닙니다.

0

서버

const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'); 

return this.http.post<TokenResponse>('/api/auth/login/', body, {headers: headers}) 
      .map(res => { 
       return {token: res.auth_token}; 
      }).catch((error: HttpErrorResponse) => { 
       if (err.error) { 
        console.log(err.error); 
       } 
       return _throw(err); 
     }); 
+0

content-type을 설정해도이 문제는 해결되지 않습니다. 실제로 content-type은 명시 적으로 설정하지 않고 이미'json' 이벤트에 있습니다. – h4k1m