Angular 4
에 Http
요청이 있습니다. 내장 된 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);
}
);
오류 개체의 json은 개체가 아닌 문자열로 서식이 지정됩니다. 서버를 제어합니까? 그렇다면 오류 개체 주변의 따옴표를 제거하여 문제를 해결하십시오. 그렇지 않은 경우 JSON.parse를 사용하여 응답을 구문 분석하십시오. – bryan60
https://github.com/angular/angular/issues/18682 – jonrsharpe
@ bryan60 예 서버에서 반환 한 데이터를 제어 할 수 있지만 'curl'이 응답을 반환하므로 문제가 발생하지 않는다고 생각합니다. 명령 줄에서 괜찮 으면 (즉, json 객체) – h4k1m