user8165785
user8165785

Reputation:

Angular 6 not getting response from expressjs node server

help a noob out, I am building a MEAN stack app and i ran into a problem where I cannot read a response from the express server but the response is generated when I use postman, here is my code

auth.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { map } from 'rxjs/operators';

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

authToken: any;
user: any;
constructor(private http:Http) { }

registerUser(user){
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  return this.http.post('http://localhost:3000/users/register',user, 
{headers: headers})
.pipe(map(res => res.json));
}

authenticateUser(user){
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  return this.http.post('http://localhost:3000/users/authenticate',user, 
  {headers: headers})
    .pipe(map(res => res.json));
 }
}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';

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

  username: String;
  password: String;
  constructor(private authService: AuthService,
   private router: Router,
   private flashMessage: FlashMessagesService
  ) { }

  ngOnInit() {
  }

  onLoginSubmit(){
  const user = {
  username: this.username,
  password: this.password
  }
  this.authService.authenticateUser(user).subscribe(data => {
    console.log(data);
   });
  }
  }

Chrome Console

ƒ () {                                         login.component.ts:29
    if (typeof this._body === 'string') {
        return JSON.parse(this._body);
    }
    if (this._body instanceof ArrayBuffer) {
        return JSON.parse(this.text());

Below is the response in Postman :

raw data...application/json login data and server response

Upvotes: 1

Views: 72

Answers (2)

Ankit Sharma
Ankit Sharma

Reputation: 1704

The error is in your pipe function.

pipe(map( res => res.json ))

You need to call res.json() inside your map. Convert it to

pipe(map( res => res.json() ))

However, converting the response to JSON is not required over Angular v5.


Correct code is as below:-

 authenticateUser(user){
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  return this.http.post('http://localhost:3000/users/authenticate',user, 
  {headers: headers})
    .pipe(map(res => res.json()));
 }

Upvotes: 2

graycodes
graycodes

Reputation: 363

Looks like data coming from authenticateUser is a function. Have you tried calling it?

Upvotes: 0

Related Questions