POST上的Angular 6 HttpErrorResponse(状态为200) [英] Angular 6 HttpErrorResponse on POST with 200 status
问题描述
使用Angular 6客户端,我访问http://localhost:8082/login
以发送username
和password
并返回令牌.
这是错误
请注意,在error:
下有我想要的令牌.
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.
这是邮递员的样子
这是我在Angular上使用的功能,用于使用给定的用户名和密码来获取令牌
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});
}
我只想返回令牌,就像在邮递员中一样.我尝试了toPromise()
,但出现了更多错误.
I want just to return the token, like in Postman. I tried toPromise()
but I've got even more errors.
推荐答案
默认情况下,Angular HttpClient尝试将HTTP响应的主体解析为JSON. 由于您收到的响应正文是纯文本,例如"Bearer ....."(不是JSON),则JSON解析失败.
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.
您需要告诉HttpClient期望纯文本响应,如下所示:
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'});
还要注意,由于响应是字符串,因此您不应该尝试将其强制转换为用户(请勿执行<User>
位);外发消息是用户,返回值是一个字符串.
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.
这篇关于POST上的Angular 6 HttpErrorResponse(状态为200)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!