What I want to do: Frontend sends username and password to the backend. Backend checks it, generates a random string, and sends back that string to the frontend. Frontend saves that string to localStorage.
In the backend:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String login(String credentials){
return this.service.login(credentials);
}
this.service.login
returns a string if username and password in credentials
is OK or returns null
if not.
In the frontend:
public login(username: string, password: string ){
return this.http.post<string>(this.authUrl, JSON.stringify({username: username, password: password}), this.getHeaders())
.pipe(
tap(
(token:string) => {
if(token){
localStorage.setItem('accessToken',token);
console.log(`Successful login for username =${username} with password=${password} and token=${token}` );
} else {
console.log(`Login failed for username =${username} with password=${password} and token=${token}`);
}
}
)
);
}
getHeaders(): {headers: HttpHeaders } {
const httpOptions = {
headers: new HttpHeaders(
{
'Content-type': 'application/json',
'responseType': 'text'
}
)
};
return httpOptions;
}
If I try to login with wrong username and password, this gets logged: Login failed for username =something with password=something and token=null
So the returning null part works, But if I send the correct username and password, I get this error:
ERROR
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/login", ok: false, …}
error: {error: SyntaxError: Unexpected token M in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "MTMyOTUz"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/login"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/login"
__proto__: HttpResponseBase
So it has some JSON.parse problem? Does it expect a JSON so doesn't know what to do with a string? What's a solution to this?