How can I access the token which is saved in the header using angular

Viewed 226

I am sending the 'auth-token' which is generated with JWT to the frontend which is built in angular. The backend is built in nodejs. when I try to access the auth-token variable from the frontend it is saying syntax error. How can access this header token in my angular code?

Frontend Request in the component

 onSubmit(){
    if(!this.signinForm.valid){
      return;
    }

    const userDetails: SigninAccount = {
      email: this.signinForm.controls.email.value,
      password: this.signinForm.controls.password.value
    }

    this.loginservice.loginUser(userDetails).subscribe(
      data => { console.log(data);
        this.router.navigate(['/'])
      },
      error => { console.log(error.error)}
    )
   

  }

Frontend service and the headeroptions

  const loginhttpOptions = {
   headers: new HttpHeaders({
     'Content-Type': 'application/json',
   })
  } 

  loginUser(user: SigninAccount): Observable<SigninAccount> {
    const makeReqURL = `${this.apiURL}/login`;
    const loginUser = this.http.post<SignupAccount>(makeReqURL, user, httpOptions)
    return loginUser;
  }

Backend response

   const userToken = jwt.sign({ _id: user._id }, process.env.TOKEN);
    res.header('auth-token', userToken).send(userToken)

Screenshot of the image in the browser and the syntax error message which is given because of the console.log(data).

enter image description here

the "text" has the JWT token too which is the same as the "auth-token" but don't know how to access it in the code and I don't know what is the syntax error either.

Please help. Thank you very much in advance.

1 Answers

There must be some syntax issue in backend code that's why you getting the error. Use some linter like EsLint which can help detecting the error.

How to access the authToken?

Here is your new backend code.

don't set token in header instead send as a json.

   const userToken = jwt.sign({ _id: user._id }, process.env.TOKEN);
    res.json({token: userToken});

The frontend code is correct you gonna get your token in console.


this.loginservice.loginUser(userDetails).subscribe(
      data => { 
        console.log(data);
        const token = data.token;
        //Save to localStorage
        localStorage.setItem('token',token);
        this.router.navigate(['/']);
      },
      error => { console.log(error.error)}

Related