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);
};