I have been trying to receive a JWT token from my web api through my angular web app. I am able to successfully retrieve the JWT token string, but I am receiving a parsing error that I cannot seem to fix.
This is the response after I send the correct credentials via POST to my web api endpoint:
Object { headers: {…}, status: 200, statusText: "OK", url: "http://localhost:52706/api/auth/token", ok: false, name: "HttpErrorResponse", message: "Http failure during parsing for http://localhost:52706/api/auth/token", error: {…} }
As you can see, I am getting a 200ok response and the token is actually in the console when I expand the error:
error: {…}
error: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
onLoadhttp://localhost:4200/vendor.js:28768:46invokeTaskhttp://localhost:4200
text: "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiQ29keVdpbHNvbiIsIlVzZXJSb2xlIjoiQWRtaW4iLCJPcmdJRCI6.dIOAIODWIOJDJjwiadjoiawjdjoiAOIJWDijoawdji838DHWJHio"
Here is my Angular login funtion:
loginUser(user) {
const creds = user.username + ":" + user.password;
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
Authorization: "Basic" + btoa(creds)
})
};
return this.http.post<any>(this._loginUrl, user, httpOptions);
}
Here is my login-component typescript:
loginUser() {
//console.log(this.loginUserData);
this._authentication
.loginUser(this.loginUserData)
.subscribe(res => console.log(res), err => console.log(err));
}
Thank you.
答案 0 :(得分:1)
Are you getting a JSON object back or just the JWT as a string? If you are getting the JWT as a string then JSON parse will fail because there is no JSON in the response.
Add responseType: 'text'
to your httpOptions
to handle a return string.
loginUser(user) {
const creds = user.username + ":" + user.password;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Basic' + btoa(creds)
}),
responseType: 'text'
};
return this.http.post(this._loginUrl, user, httpOptions);
答案 1 :(得分:1)
To prevent Angular trying to parse your token as a JSON, you need to set responseType: 'text'
.
Try this:
loginUser(user) {
const creds = user.username + ":" + user.password;
const headers = new HttpHeaders({
"Content-Type": "application/json",
Authorization: "Basic" + btoa(creds)
});
return this.http.post<any>(this._loginUrl, user, {
headers: headers,
responseType: 'text'
});
}