antoniodela
antoniodela

Reputation: 51

Angular POST request does not work

I'm using Express and Node to make the API and Angular to hit the POST request. The api is working fine, as I have tested in Postman. The problem comes with the Angular code, when I use this function it does nothing.

This is the authService:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators/map';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { of } from 'rxjs/observable/of';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const url = 'http://localhost:7171/login';

@Injectable()
export class AuthService {

  constructor(private http: HttpClient) { }
  login(username: string, password: string) {
    //do not need to stringify your body
    const body = {
        username, password
    }
    console.log(this.http.post(url));
    return this.http.get(url);
}

}

This is the authComponent

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';

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

  username: '';
  password: '';

  constructor(private router: Router, private auth: AuthService) { }

  login() {
    console.log(this.username, this.password);
    this.auth.login(this.username, this.password);
  }

  ngOnInit() {
  }
}

This is the code from express:

const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const async = require("async");


var connection = mysql.createConnection({
   [...]);


router.post('/login', function(req, res) {
    var inputName = req.body.user;
    var inputPass = req.body.password;
    console.log('Usuario: ' + inputName + '\nContraseña: '+inputPass);
    res.status(200).json({
        message: 'It Works',
        usuario: inputName,
        password: inputPass
    })
});

module.exports = router;

Upvotes: 1

Views: 214

Answers (1)

Dániel Kis
Dániel Kis

Reputation: 2631

You have called the this.auth.login(this.username, this.password) but you never used the result. The auth.login returns an Observable you need to subscribe to result like this:

this.auth.login(this.username, this.password)
         .subscribe(result => {
                       alert('OK');
                    }, 
                    error => {
                       alert('error occured');
                    });

Upvotes: 2

Related Questions