问题描述
使用我的 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 errorNotice that, under error:
there is the token that I want.
这就是 Postman 上的样子
This is how it looks on Postman
这是我在 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});
}
我只想返回令牌,就像在 Postman 中一样.我试过 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'});
另请注意,由于响应是字符串,因此您不应该尝试将其强制转换为用户(不要执行 位);传出消息是用户,返回值是一个字符串.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!