Search code examples
node.jsangularangular-httpclient

How to correctly send post request


I'm setting up a web app in Angular with a restAPI in Nodejs but I can't correctly set my post request for authenticate user

I've set up my api and I can correctly test it with curl but in the client side (angular) it can't pass the condition that verify that the field required are presents

function in the API:

exports.authenticate = function(req, res) {
  var new_user = new User(req.body);
  if (!new_user.login || !new_user.pwd) {
    res.status(400).send({
      error: true,
      message: 'Please provide all informations!'
    });
  } else {
    User.authenticate(new_user, function(err, user) {
      console.log('controller');
      if (err) {
        res.status(500).send(err);
      } else {
        console.log(user[0].id);
        var token = jwt.sign({
          id: user[0].id
        }, config.secret, {
          expiresIn: 3600
        });
        res.status(200).send({
          user: user,
          auth: true,
          token: token
        });
      }
    });
  }
}

User.authenticate call my sql query:

sql.query("SELECT * FROM user WHERE login = ?", [user.login], function(err, res) {
  if (err) {
    return res.status(500).send('Error  on the server ', err);
    //console.log("error select: ", err);
  } else {
    if (!res) {
      return res.status(404).send('No user found');
    } else {

      //sql.query("UPDATE user SET pwd = ? WHERE id = ?", [crypto.createHash('sha256').update(user.
      sql.query("SELECT * FROM user WHERE pwd = ?", [crypto.createHash('sha256').update(user.pwd + r
        if (err) {
          console.log("error: ", err);
          result(null, err);
        } else {


          result(null, res2);
        }
      });
    }
  }
});

Angular side (my service function):

login(loguser: User) {
       return this.http.post<any>(`${environment.apiUrl}/authenticate`,
               { loguser }, { headers: new HttpHeaders().set('Content-Type', 'application/json')})

                       .pipe(map(user => {
                               // store user details and jwt token in local storage to keep user logged in between p
                               localStorage.setItem('currentUser', JSON.stringify(user));
                               this.currentUserSubject.next(user);
                               return user;
               }));
       }

login component:

onSubmit() {
  this.submitted = true;
  // stop here if form is invalid
  if (this.loginForm.invalid) {
    return;
  }

  this.loading = true;
  this.user.login = this.f.username.value;
  this.user.pwd = this.f.password.value;
  console.log(this.user);
  this.authenticationService.login(this.user)
    .pipe(first())
    .subscribe(
      data => {
        this.router.navigate([this.returnUrl]);
      },
      error => {
        this.error = error;
        this.loading = false;
     });
   }

console.log(this.user) output : {login: "cl", pwd: "cl"}

my post request is blocked in this part of my api:

if (!new_user.login || !new_user.pwd){
  res.status(400).send({ error: true, message: 'Please provide all informations!' });

Because this is the answer I get when I submit the form.

I can get right answer when I test it like that:

curl -v -X POST --data '{"login":"cl","pwd":"cl"}' --header "Content-Type: application/json" https://@api:8443/autenticate

I want to get the good answer.


Solution

  • The problem is in your Angular code:

    login(loguser: User) {
      return this.http.post<any>(`${environment.apiUrl}/authenticate`, 
        { loguser }, 
        {
          headers: new HttpHeaders().set('Content-Type', 'application/json')
        })
        .pipe(map(user => {
          // store user details and jwt token in local storage to keep user logged in between p
          localStorage.setItem('currentUser', JSON.stringify(user));
          this.currentUserSubject.next(user);
          return user;
        }));
    }
    

    This piece of code:

    { loguser }
    

    uses the "shortcut property name" syntax introduced in TypeScript and ECMAScript 2015 to create an object with a single property named loguser which has the value of the loguser variable. It is equivalent of writing:

    { loguser: loguser }
    

    Instead, you can just pass the variable itself in your code:

    login(loguser: User) {
      return this.http.post<any>(`${environment.apiUrl}/authenticate`, 
        loguser, // Just the object itself
        {
          headers: new HttpHeaders().set('Content-Type', 'application/json')
        })
        .pipe(map(user => {
          // store user details and jwt token in local storage to keep user logged in between p
          localStorage.setItem('currentUser', JSON.stringify(user));
          this.currentUserSubject.next(user);
          return user;
        }));
    }
    

    That will pass the object, with the login and pwd properties intact.