0

Hi guys i'm currently working on a simple singup and singin code with Angular for frontend and Express, Typescript, JWT and Mongodb for the API REST.

When i send the post method on Postman it gives me the header with the token but when i'm sending the post method through the client side i'm getting the header with the token as undefined and don't know why, could you help me?

Here it's my code

Auth.service.ts

import { Component, OnInit } from '@angular/core';

import { AuthService } from '../../services/auth.service';


@Component({
  selector: 'app-registrar',
  templateUrl: './registrar.component.html',
  styleUrls: ['./registrar.component.css']
})
export class RegistrarComponent implements OnInit {


  user = {
    username: '',
    email: '',
    password: ''
  };

  constructor(private authService: AuthService) { }

  ngOnInit(): void {
  }

  registrar(){
    this.authService.registrar(this.user)
      .subscribe(
        res => {
          console.log(res.token);
          // localStorage.setItem('token', res['token']);
        },
        err => console.log(err)
      );
  }

}

Registrar.component.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private URL = 'http://localhost:3000/api/auth/';

  constructor(private http: HttpClient) { }

  registrar(user){
    return this.http.post<any>(this.URL + 'registrar', user);
  }

}

Auth.controller.ts -- API REST

import { Request, Response } from 'express';
import User, { IUser } from '../models/user';
import jwt from 'jsonwebtoken';

export const registrar = async (req: Request, res: Response) => {
   console.log(req.body);
   const user: IUser = new User ({
      username: req.body.username,
      email: req.body.email,
      password: req.body.password
   });
   user.password = await user.encriptarPassword(user.password);
   const usuarioGuardado = await user.save();

   const token: string = jwt.sign({_id: usuarioGuardado._id}, process.env.TOKEN_SECRET || 'secretKey');

   res.header('Token', token).json(usuarioGuardado);
};

export const logear = async (req: Request, res: Response) => {
   const user = await User.findOne({email: req.body.email});
   if (!user) return res.status(400).json('El email es incorrecto');

   const claveCorrecta: boolean = await user.validarPassword(req.body.password);
   if (!claveCorrecta) return res.status(400).json('La contraseña es incorrecta');

   const token: string = jwt.sign({_id: user._id}, process.env.TOKEN_SECRET || 'secretKey', {
      expiresIn: 60 * 60 * 24
   });

   res.header('token', token).json(user);
};

export const perfil = async (req: Request, res: Response) => {
   const user = await User.findById(req.userId, { password: 0 });
   if (!user) return res.status(404).json('Usuario no encontrado');
   res.json(user);
};

Here is a pic of console.log(res.token)

  • Simplest solution is to add token in user object server side. Otherwise, you need to modify your angular call to read response headers – David Apr 27 '20 at 06:19
  • How could you change my angular call to read response headers? I will try to add the token to my user object server side but how can i solve this on my angular? – Andres Palacios Apr 27 '20 at 07:28
  • Hi, have a look at this post: https://stackoverflow.com/questions/48184107/read-response-headers-from-api-response-angular-5-typescript – Fel Apr 27 '20 at 13:38

1 Answers1

0

Since you are sending the token as a header, you need to read the headers client side.

Modify your service registrar method to return the whole response (so headers and body)

return this.http.post<any>(this.URL + 'registrar', user, { observe: 'response'});

And then in your component

this.authService.registrar(this.user)
  .subscribe(        resp => {
   let token = resp.headers.get('token');
   let user = resp.body
  });

For a quick fix you could also just add the token in the body server side.

David
  • 33,444
  • 11
  • 80
  • 118
  • Now i'm getting null as a value. What's the best method to get the token? as a header or on the server side? On my server side i just need to add token to the user right? I'm new on this thing sorry – Andres Palacios Apr 27 '20 at 08:23
  • Show a screenshot of your response headers in the chrome network debugger. The easiest yould be to just add it to the user object server side, and retrieve it like you already did before. – David Apr 27 '20 at 09:08
  • Try `.get('Token')` (with a capital T). If they does not work check if there is any error in the console – David Apr 27 '20 at 09:47
  • Still getting null http://prntscr.com/s6z7r1 Can you tell me how can i add the token to my object? – Andres Palacios Apr 27 '20 at 19:47
  • `usuarioGuardado.token = token`? – David Apr 27 '20 at 21:18