简体   繁体   中英

undefined variable res while trying to login using angular / spring security

i'm trying to authenticate using angular / spring security

my backend work perfectly.

the problem is with this function which is reponsible for login:

  onFormSubmit(authBody: authBody ) {

    this.authService.login(authBody)
      .subscribe(res => {
        console.log(res);
        if (res.token) {
          localStorage.setItem('token', res.token);
          this.router.navigate(["/menu"]);
        }
      }, (err) => {
        console.log(err);
      });
  }

console.log(res) return: {username=med, token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtZWQiLCJyb2xlcyI6W10sImlhdCI6MTYzOTA2NzgzOSwiZXhwIjoxNjM5MDcxNDM5fQ.a-DzNNeVRZ6XUPwYnzAk_P_0yFQO5GXwvBds_7RvGs8}

i try to get the token from this object, but when testing with if(res.token) it return undefined.

this my authentification method service:

login(authBody: authBody): Observable<any> {
    console.log(authBody.username);
    return this.http.post(apiUrl + this.aPILogin, authBody ,{responseType: 'text'})
      .pipe(
        tap(_ => this.isLoggedIn = true),
        catchError(this.handleError('login', []))
      );
  }

any suggestion pleaaase?

Thank youuuu

Since you defined the responseType as text, your getting a string from the observable, not an object .

For this to work as you expect you have to do two things:

1.- Return a proper JSON from the server. (Can't help you with that cause I've never used Spring).

2.- Remove the responseType( its default value is json) so the response body gets parsed into an object.

cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM