Angular 6 HttpErrorResponse on POST with 200 status

六眼飞鱼酱① 提交于 2020-01-13 06:09:13

问题


With my Angular 6 client I access the http://localhost:8082/login to send username and password and return a token. This is the error Notice that, under error: there is the token that I want.

This is how it looks on Postman

And this is the function I use on Angular to get the token with the given username and password

validateUser(user:User){


    var reqHeader = new HttpHeaders({ 'Content-Type': 'application/json','No-Auth':'True' });



    return this.httpClient.post<User>(this.apiURL + '/login',user,{headers:reqHeader});
  }

I want just to return the token, like in Postman. I tried toPromise() but I've got even more errors.


回答1:


By default, the Angular HttpClient tries to parse the body of the HTTP response as JSON. Since the response body that you are receiving is plain text, e.g. "Bearer .....", and not JSON, the JSON parse is failing.

You need to tell the HttpClient to expect a plain text response, like this:

this.httpClient.post(this.apiURL + '/login', user, {headers:reqHeader, responseType: 'text'});

Also note that since the response is a string, you should not be trying to cast it to a User (don't do the <User> bit); The outgoing message is the User, the return value is a string.



来源:https://stackoverflow.com/questions/53605619/angular-6-httperrorresponse-on-post-with-200-status

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!