Angular 6未从ExpressJS节点服务器获得响应

时间:2018-08-24 10:45:57

标签: node.js angular

帮助菜鸟,我正在构建MEAN堆栈应用程序,但遇到了一个问题,我无法读取快递服务器的响应,但是使用邮递员时会生成响应,这是我的代码

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控制台

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

以下是邮递员中的回复:

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

2 个答案:

答案 0 :(得分:2)

错误出在您的pipe函数中。

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

您需要在地图内致电res.json()。将其转换为

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

但是,Angular v5不需要将响应转换为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()));
 }

答案 1 :(得分:0)

类似data的{​​{1}}是一个函数。您尝试过打电话吗?