javascript – ERROR HttpErrorResponse { headers: HttpHeaders, status: 500 Cannot read properties of undefined (reading ’email’)

backend> routes>user.js

const express = require("express");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken")

const User = require("../model/user");
// const user = require("../models/user");

const router = express.Router();

router.post("/signup", (req, res, next) => {
  bcrypt.hash(req.body.password, 10)
    .then(hash => {
      const user = new User({
        email:req.body.email,
        password: hash
      })
      user.save()
        .then(result => {
          res.status(201).json({
            message:'User created!',
            result: result
          })
      })
      .catch(err => {
        res.status(500).json({
          error: err
        })
      })
    })
})

router.post("/login",(req,res,next) => {
  let fetchedUser;
  User.findOne({email:req.body.email})
    .then(user =>  {
      if (!user){
        return res.status(401).json({
          message:"Auth failed"
        })
      }
      fetchedUser = user;
      return bcrypt.compare(req.body.password, user.password)
    })
    .then(result => {
      if (!result){
        return res.status(401).json({
          message:"Auth failed"
        })
      }
      const token = jwt.sign(
        {email:fetchedUser.email, id:fetchedUser._id},
        'this_secret_should_be_longer',
        {expiresIn:"1h"}
      )
      res.status(200).json({
        token:token,
        expiresIn: 3600
      })

    })
    .catch(err => {
      return res.status(401).json({
        message:"Auth failed"
      })
    })
})


module.exports = router;

backend>app.js

const path = require("path")
const express = require("express")

const mongoose = require("mongoose")


const userRoutes = require("./routes/user")

const app = express();



mongoose.connect("mongodb+srv://username:password@cluster0.1qoba.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
.then(() => {
  console.log("Connected to database")
})
.catch(() => {
  console.log("Connection failed")
})



app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");


  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
  
  next();
})



app.use("/api/user", userRoutes)



module.exports = app

src>app>auth>login>login.component.ts

import { Component } from "@angular/core";
import { NgForm } from "@angular/forms";
import { AuthService } from "../auth.service";

@Component({
  templateUrl:"./login.component.html",
  styleUrls : ["./login.component.css"]
})

export class LoginComponent{

  isLoading : boolean = false;

  constructor (public authService : AuthService){}

  onLogin(form:NgForm){
    console.log(form.value)
    if(form.invalid){
      return
    }
    // this.isLoading = true
    this.authService.login(form.value.email, form.value.password)

  }
}

src>app>auth>signup>signup.component.ts

import { Component } from "@angular/core";
import { NgForm } from "@angular/forms";
import { AuthService } from "../auth.service";

@Component({
  templateUrl:"./signup.component.html",
  styleUrls: ["./signup.component.css"]
})

export class SignupComponent{

  isLoading = false;

  constructor (public authService : AuthService){}

  onSignup(form:NgForm){
      // console.log(form.value)
    if(form.invalid){
      return
    }
    // this.isLoading=true
    this.authService.createUser(form.value.email, form.value.password)
  }
}

src>app>auth>auth-service.ts

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

import { AuthData } from "./auth-data.model";

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

  constructor (private http : HttpClient) {}

  createUser(email: string, password: string){
    const authData : AuthData = {email: email, password: password}
    this.http
      .post("http://localhost:3000/api/user/signup", authData )
      .subscribe(response => {
        console.log(response)
      })
  }

  login(email:string, password:string){
    const authData : AuthData = {email: email, password: password}
    this.http.post("http://localhost:3000/api/user/login", authData)
    .subscribe(response => {
      console.log(response)
    })
  }
}

app.routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './auth/login/login.component';
import { SignupComponent } from './auth/signup/signup.component';

const routes: Routes = [
  {path:'login', component:LoginComponent},
  {path:'signup', component:SignupComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';



import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import {FormsModule, ReactiveFormsModule } from '@angular/forms';
import {MatInputModule} from '@angular/material/input';
import {MatCardModule} from '@angular/material/card';
import {MatButtonModule} from '@angular/material/button';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatExpansionModule} from '@angular/material/expansion';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {MatPaginatorModule} from '@angular/material/paginator';
import { LoginComponent } from './auth/login/login.component';
import { SignupComponent } from './auth/signup/signup.component';
import { HeaderComponent } from './header/header.component';
import {HttpClientModule} from '@angular/common/http'

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    SignupComponent,
    HeaderComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MatInputModule,
    MatCardModule,
    MatButtonModule,
    MatToolbarModule,
    MatExpansionModule,
    MatProgressSpinnerModule,
    MatPaginatorModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

The problem that I face in the console of client-side is – ERROR HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: ‘Internal Server Error’

The problem that I get in the terminal of my IDE is – Cannot read properties of undefined (reading ‘password’) and Cannot read properties of undefined (reading ’email’).

Whenever I enter email address and password and after clicking that I got these errors in the console and terminal.

Leave a Comment