title: zone-evergreen.js:2845 POST http://127.0.0.1:3000/auth/login net::ERR_CONNECTION_REFUSED
body: <p>I am trying to be connected to my application by the login form via the API
  I have this error when i submit my login form.</p>
  <p>This is my frontend:</p>
  <p>my loginComponent.ts</p>
  <pre><code>import { AuthentificationService } from './../service/authentification.service';
  import { Component, OnInit, ViewChild } from '@angular/core';
  import { Router } from '@angular/router';
  import { FormControl, NgForm, Validators, FormGroup } from '@angular/forms';
  
  @Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
  })
  export class LoginComponent implements OnInit {
    @ViewChild(&quot;formDirective&quot;) formDirective: NgForm;
  
    loginForm: FormGroup;
  
    constructor(private authService: AuthentificationService, private routes: Router) { }
  
    ngOnInit(): void {
       this.loginForm = this.createFormGroup();
    }
  
    createFormGroup(): FormGroup {
      return new FormGroup({
        username: new FormControl(&quot;&quot;, [Validators.required]),
        password: new FormControl(&quot;&quot;, [Validators.required])
      });
    }
  
    login(): void {
      console.log(`Username: ${this.loginForm.value.username}\n Password: ${this.loginForm.value.password}`)
      this.authService.login(this.loginForm.value.username, this.loginForm.value.password).subscribe();
    }
  }
  
  </code></pre>
  <p>My LoginComponent.html</p>
  <pre><code>&lt;mat-card fxFlex=&quot;25&quot; fxFlex.xs=&quot;90%&quot; fxFlex.sm=&quot;33%&quot;&gt;
  
    &lt;mat-toolbar color=&quot;primary&quot;&gt;Page de connection&lt;/mat-toolbar&gt;
    &lt;form
     fxFlexLayoutAlign=&quot;stretch&quot;
     fxLayout=&quot;column&quot;
     class=&quot;login-form&quot;
     [formGroup]=&quot;loginForm&quot;
     #formDirective=&quot;ngForm&quot;
     (ngSubmit)=&quot;login()&quot;
     novalidate&gt;
  
      &lt;mat-form-field&gt;
        &lt;mat-label&gt;Nom d'utilisateur&lt;/mat-label&gt;
        &lt;input matInput placeholder=&quot;Nom d'utilisateur&quot; formControlName=&quot;username&quot;&gt;
      &lt;/mat-form-field&gt;
  
      &lt;mat-form-field&gt;
        &lt;mat-label&gt;Mot de passe&lt;/mat-label&gt;
        &lt;input matInput type=&quot;password&quot; placeholder=&quot;Mot de passe&quot; formControlName=&quot;password&quot;&gt;
      &lt;/mat-form-field&gt;
  
      &lt;button color=&quot;primary&quot; [disabled]=&quot;!loginForm.valid&quot; mat-raised-button type=&quot;submit&quot;&gt;
        &lt;span&gt;Connection&lt;/span&gt;
      &lt;/button&gt;
  
    &lt;/form&gt;
  &lt;/mat-card&gt;
  
  </code></pre>
  <p>my AuthService.ts</p>
  <pre><code>import { ErrorHandlerService } from './error-handler.service';
  import { User } from '../Model/user.model';
  import { Router } from '@angular/router';
  import { Injectable } from '@angular/core';
  import { HttpClient, HttpHeaders } from '@angular/common/http';
  import { BehaviorSubject, Observable } from 'rxjs';
  import { first, catchError, tap } from 'rxjs/operators';
  @Injectable({
    providedIn: 'root'
  })
  export class AuthentificationService {
  
    private url = &quot;http://127.0.0.1:3000/auth/login&quot;;
    httpOptions: { headers: HttpHeaders } = {
      headers: new HttpHeaders({&quot;Content-type&quot;: &quot;application/json&quot;})
    };
    isUserLoggedIn = new BehaviorSubject&lt;boolean&gt;(false);
    userId: Pick&lt;User, &quot;Id_utilisateur&quot;&gt;;
    constructor(private router: Router, private http: HttpClient, private errorHandlerService: ErrorHandlerService) { }
    login(username: Pick&lt;User, &quot;nom_utilisateur&quot;&gt;, password: Pick&lt;User, &quot;Mot_de_passe&quot;&gt;): Observable&lt;{
      token: string; userId: Pick&lt;User, &quot;Id_utilisateur&quot;&gt;
    }&gt; {
      try {
        return this.http.post(this.url, {username, password}, this.httpOptions).pipe(
          first(),
          tap((tokenObject: { token: string; userId: Pick&lt;User, &quot;Id_utilisateur&quot;&gt; }) =&gt; {
            this.userId = tokenObject.userId;
            localStorage.setItem('token', tokenObject.token);
            this.isUserLoggedIn.next(true);
            this.router.navigate([&quot;accueil&quot;]);
          }),
          catchError(this.errorHandlerService.handleError&lt;{
            token: string; userId: Pick&lt;User, &quot;Id_utilisateur&quot;&gt;
          }&gt;(&quot;login&quot;))
        );
      } catch (error) {
        console.log(error);
      }
    }
  }
  
  </code></pre>
  <p>My backend now</p>
  <p>index.js</p>
  <pre><code>
  const cors = require('cors');
  const express = require('express');
  const bodyParser = require('body-parser');
  const errorController = require('./controller/errorController');
  const authRoutes = require('./routes/authRoutes');
  
  const app = express();
  
  app.use(cors());
  
  const ports = process.env.PORT || 3000;
  
  app.use(bodyParser.json());
  
  app.use((req, res, next) =&gt; {
    res.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE,OPTIONS, PATCH');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.setHeader('Access-Control-Allow-Headers','*');
      res.setHeader('Access-Control-Allow-Credentials','true');
    next();
  });
  
  app.use('/auth', authRoutes);
  
  
  app.use(errorController.get404);
  app.use(errorController.get500);
  
  app.listen(ports, () =&gt; {
    console.log(`Listening on port ${ports}`);
  } );
  </code></pre>
  <p>config.json</p>
  <pre><code>{
    &quot;host&quot;: &quot;127.0.0.1&quot;,
    &quot;user&quot;: &quot;root&quot;,
    &quot;password&quot;: &quot;&quot;,
    &quot;database&quot;: &quot;fdss&quot;
  }
  </code></pre>
  <p>UserModel.js</p>
  <pre><code>const db = require('../util/database');
  
  module.exports = class utilisateurModel {
    constructor(Nom, Prenom, nom_utilisateur, Institution, Role, Mot_de_passe, Num_telephone, Email, Observation) {
      this.Nom = Nom;
      this.Prenom = Prenom;
      this.nom_utilisateur = nom_utilisateur;
      this.Institution = Institution;
      this.Role = Role;
      this.Mot_de_passe = Mot_de_passe;
      this.Num_telephone = Num_telephone;
      this.Email = Email;
      this.Observation = Observation;
    }
  
    static find(nom_utilisateur) {
      try {
        return db.execute(
          'SELECT * FROM utilisateur WHERE nom_utilisateur = ?', [nom_utilisateur]
        );
      } catch (error) {
        console.log(error)
      }
     
    }
  
    static save(utilisateur){
      try {
        return db.execute(
          'INSERT INTO utilisateur (Nom,  Prenom, nom_utilisateur, Institution, Role, Mot_de_passe,'+
             'Num_telephone, Email, Observation) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
          [utilisateur.Nom, utilisateur.Prenom, utilisateur.nom_utilisateur, utilisateur.Institution, utilisateur.Role,
            utilisateur.Mot_de_passe, utilisateur.Num_telephone, utilisateur.Email, utilisateur.Observation]
        );
      } catch (error) {
        console.log(error);
      }
     
    }
  
  };
  </code></pre>
  <p>database.js</p>
  <pre><code>const mysql = require('mysql2');
  
  const config = require('../config/config.json');
  
  const pool = mysql.createPool({
    host: config.host,
    user: config.user,
    database: config.database,
    password: config.password
  });
  
  module.exports = pool.promise();
  </code></pre>
  <p>authController.js</p>
  <pre><code>const UserModel = require('../model/UserModel');
  const jwt = require('jsonwebtoken');
  exports.login = async (req, res, next) =&gt; {
    const nom_utilisateur = req.body.nom_utilisateur;
    const Mot_de_passe = req.body.Mot_de_passe;
    try {
      const user = await UserModel.find(nom_utilisateur);
      if(user[0].length !== 1){
        const error = new Error('l\'utilisateur avec ce nom d\'utilisateur n\'a pas été trouver');
        error.statusCode = 401;
        throw error;
      }
      const storedUser = user[0][0];
      if(Mot_de_passe !== storedUser.Mot_de_passe) {
        const error = new Error('Mot de passe erroné!.');
        error.statusCode = 401;
        throw error; 
      }
      const token = jwt.sign(
        {
          nom_utilisateur: storedUser.nom_utilisateur,
          userId: storedUser.Id_utilisateur
        },
        'secretfortoken',
        {expiresIn: '1h'}
      );
      res.status(200).json({token: token, userId: storedUser.Id_utilisateur});
    } catch (err) {
      if (!err.statusCode) {
        err.statusCode = 500;      
      }
      next(err);
    }
  }
  </code></pre>
  <p>authRoutes.js</p>
  <pre><code>const express = require('express');
  
  const router = express.Router();
  
  const authController = require('../controller/authController');
  
  
  router.post('/login', authController.login);
  
  module.exports = router;
  </code></pre>
  <p>I have this error in my terminal when I submit the button :</p>
  <pre><code> Api\node_modules\mysql2\lib\pool.js:177
          throw e;
          ^
  
  TypeError: Bind parameters must not contain undefined. To pass SQL NULL specify JS null
      at D:\TP Web\AngularFundamental\AppFdss\Api\node_modules\mysql2\lib\connection.js:592:17
      at Array.forEach (&lt;anonymous&gt;)
      at PoolConnection.execute (D:\TP Web\AngularFundamental\AppFdss\Api\node_modules\mysql2\lib\connection.js
  :584:22)
      at D:\TP Web\AngularFundamental\AppFdss\Api\node_modules\mysql2\lib\pool.js:172:14
      at D:\TP Web\AngularFundamental\AppFdss\Api\node_modules\mysql2\lib\pool.js:64:16
      at PoolConnection.&lt;anonymous&gt; (D:\TP Web\AngularFundamental\AppFdss\Api\node_modules\mysql2\lib\connectio
  n.js:741:13)
      at Object.onceWrapper (events.js:422:26)
      at PoolConnection.emit (events.js:315:20)
      at ClientHandshake.&lt;anonymous&gt; (D:\TP Web\AngularFundamental\AppFdss\Api\node_modules\mysql2\lib\connecti
  on.js:110:14)
      at ClientHandshake.emit (events.js:315:20)
  [nodemon] app crashed - waiting for file changes before starting...
  </code></pre>
  <p>I have this error to the browser console when I submit the button</p>
  <pre><code>login failed: Http failure response for http://127.0.0.1:3000/auth/login: 0 Unknown Error
  zone-evergreen.js:2845 POST http://127.0.0.1:3000/auth/login net::ERR_CONNECTION_REFUSED
  </code></pre>
  <p>I look forward to your help</p>