2

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);
    }
);
7
  • the json on the error object is formatted as a string, not an object. Do you control the server? If so, fix it by getting rid of the quotes around your error object. if not, parse the response with JSON.parse Commented Oct 15, 2017 at 22:32
  • 2
    Have a look at e.g. github.com/angular/angular/issues/18682 Commented Oct 15, 2017 at 22:34
  • @bryan60 Yes I have control on the data returned by the server, but I don't think the issue is coming from there because the response returned by curl on the command line is fine (i.e. a json object) Commented Oct 15, 2017 at 22:41
  • you can create an interceptor to make all error JSON.parse and then throw it again, to the caller Commented Oct 15, 2017 at 22:44
  • I'm looking at a json formatted string in your sample, it's wrong in the sample or on the server. Objects aren't surrounded in quotes, just brackets. Everytime I use curl, it outputs the body of my response unparsed. I don't know if you have some curl json parsing plugin that I dont, but I would never think to use curl to debug json. Commented Oct 15, 2017 at 22:46

2 Answers 2

1

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);
        });
Sign up to request clarification or add additional context in comments.

1 Comment

Setting the content-type doesn't solve this issue (in fact the content-type is already in json event without explicitely setting it).
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.