Hakim
Hakim

Reputation: 3437

Angular4 - Http error returned is a string instead of an object

I'm doing an Http request in Angular 4 using its builtin HttpClient class. Everything works well, but there is a small problem with the error variable returned.

When I post the wrong username/password combination to login the user, the error object returned contains an error key for which the value is expected to be an Object but I'm getting a string instead. Please see below the text between ** in the object to understand what's the issue:

{**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"}

What might cause this kind of problem? I need to have an object there just so I can let the user know what went wrong during the authentication. I need to precise that the authentication works well when the correct credentials are provided and that I have activated CORS on the webserver I'm sending the HTTP request to.

Below is a short piece of code extracted which does the POST http request:

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

Upvotes: 2

Views: 2265

Answers (2)

Hakim
Hakim

Reputation: 3437

This error seems to have been fixed by recent versions of Angular and Angular-cli according to source, and I don't have it with Angular 4.4.6.

Upvotes: 1

ramon22
ramon22

Reputation: 3628

Try setting Content-Type to json in the headers of your post request for the server

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

Upvotes: 1

Related Questions