Reputation: 1399
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.
Upvotes: 10
Views: 10563
Reputation: 808
i have the same error
you must change the response from json to text
datatype by default is JSON
this way make new error in observable and the solution of this case
this.httpClient.post(this.apiURL + '/login', user, {headers:reqHeader, responseType: 'text'});
in a above way i think will make new error because observable and the solution in this case
ERROR in src/app/myS.service.ts(24,54): error TS2322: Type '"text"' is not assignable to type '"json"'
you must use this pattern to solution it
returnObservable(): Observable<any> {
const requestOptions: Object = {
/* other options here */
headers:reqHeader
responseType: 'text'
}
return this.http.get<any>(url, body, requestOptions);
}
Upvotes: 0
Reputation: 21
In Angular 11+ use httpOptions = { responseType: 'text' as const, }
Upvotes: 1
Reputation: 30088
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.
Upvotes: 21