1

我正在Http请求Angular 4使用它的内置HttpClient类。一切正常,但是返回的错误变量有一个小问题。

当我post使用错误的用户名/密码组合登录用户时,返回的错误对象包含一个error键,该键的值应该是一个,Object但我得到的是一个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

以下是提取的一小段代码,用于执行POSThttp 请求:

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);
    }
);
4

2 回答 2

1

尝试在您对服务器的发布请求的标头中将 Content-Type 设置为 json

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);
        });
于 2017-10-16T19:36:03.777 回答
0

这个错误似乎已经被最近的版本AngularAngular-cli根据修复了,我没有它Angular 4.4.6

于 2017-11-04T00:51:15.000 回答