Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Angular 7 HttpClient post请求未发送到nodejs服务器_Node.js_Angular_Observable_Angular Http - Fatal编程技术网

Node.js Angular 7 HttpClient post请求未发送到nodejs服务器

Node.js Angular 7 HttpClient post请求未发送到nodejs服务器,node.js,angular,observable,angular-http,Node.js,Angular,Observable,Angular Http,我的angular 7应用程序正在使用端口4200上的ng serve运行。我有一个运行在docker容器内的节点服务器,位于localhost:8081 我已经用邮递员验证了服务器已经启动并且可以访问。url是localhost:8081/login。提交POST请求时,我能够收到我期望的数据 当我单击login.html表单中的login按钮时,它会从login组件类调用onSubmit()。这将调用login(),然后从身份验证服务调用一个函数,该函数创建对localhost:8081/l

我的angular 7应用程序正在使用端口4200上的
ng serve
运行。我有一个运行在docker容器内的节点服务器,位于localhost:8081

我已经用邮递员验证了服务器已经启动并且可以访问。url是
localhost:8081/login
。提交POST请求时,我能够收到我期望的数据

当我单击login.html表单中的login按钮时,它会从login组件类调用
onSubmit()
。这将调用
login()
,然后从身份验证服务调用一个函数,该函数创建对
localhost:8081/login
的POST请求

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AuthenticationService } from 'src/app/services/authentication.service';

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

  constructor(private authenticationService: AuthenticationService) { }

  loginForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });

  ngOnInit() {
  }

  // Called when login form submits
  onSubmit() {
    this.login();
  }

  login() : void {
    this.authenticationService.login(this.loginForm.controls.email.value, this.loginForm.controls.password.value);
  }

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

import { User } from '../models/user';

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

  private currentUserSubject: BehaviorSubject<User>;
  private currentUser: Observable<User>;

  constructor(private http: HttpClient) {
    this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
    this.currentUser = this.currentUserSubject.asObservable();
  }

  public get currentUserValue(): User {
    return this.currentUserSubject.value;
  }

  login(email: string, password: string) {
    return this.http.post<any>('localhost:8081/login', {email, password})
      .pipe(map(user => {

        if (user && user.token) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
          this.currentUserSubject.next(user);
        }

        return user;
    }));
  }

  logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
    this.currentUserSubject.next(null);
  }
}
// Verifies that the email and password exist in the database.
app.post('/login', (req, res) => {
    console.log("in login post");
    res.json({ firstName: 'test', lastName: 'user', email: 'test@gmail.com', password: 'pass' });
});
authentication.service.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AuthenticationService } from 'src/app/services/authentication.service';

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

  constructor(private authenticationService: AuthenticationService) { }

  loginForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });

  ngOnInit() {
  }

  // Called when login form submits
  onSubmit() {
    this.login();
  }

  login() : void {
    this.authenticationService.login(this.loginForm.controls.email.value, this.loginForm.controls.password.value);
  }

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

import { User } from '../models/user';

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

  private currentUserSubject: BehaviorSubject<User>;
  private currentUser: Observable<User>;

  constructor(private http: HttpClient) {
    this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
    this.currentUser = this.currentUserSubject.asObservable();
  }

  public get currentUserValue(): User {
    return this.currentUserSubject.value;
  }

  login(email: string, password: string) {
    return this.http.post<any>('localhost:8081/login', {email, password})
      .pipe(map(user => {

        if (user && user.token) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
          this.currentUserSubject.next(user);
        }

        return user;
    }));
  }

  logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
    this.currentUserSubject.next(null);
  }
}
// Verifies that the email and password exist in the database.
app.post('/login', (req, res) => {
    console.log("in login post");
    res.json({ firstName: 'test', lastName: 'user', email: 'test@gmail.com', password: 'pass' });
});
我删除了另一个逻辑,这样我就可以用最简单的案例来测试它;只是返回硬编码的值

当我向邮递员发出请求时,我看到“in login post”已被记录。但是,当我从Angular发出请求时,不会记录“in login post”


为什么我不能从角度到达终点,但我可以从邮递员那里到达终点?地址和端口相同。

login.component.ts
中使用登录服务时,必须订阅您的登录服务方法

例如:

login() : void {
    this.authenticationService.login(this.loginForm.controls.email.value, this.loginForm.controls.password.value).subscribe();
  }

正如@Austraas所提到的,
可观察的
必须至少有一个活动订阅才能执行

您必须在
login组件中订阅
AuthenticationService
login()
方法

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AuthenticationService } from 'src/app/services/authentication.service';

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

  constructor(private authenticationService: AuthenticationService) { }

  loginForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });

  ngOnInit() {
  }

  // Called when login form submits
  onSubmit() {
    this.login();
  }

  login() : void {
    this.authenticationService
      .login(this.loginForm.controls.email.value, this.loginForm.controls.password.value)
      .subscribe(   // <-- Subscription required here 
        (res) => {
          console.log(res);
      });
  }

}
从'@angular/core'导入{Component,OnInit};
从'@angular/forms'导入{FormControl,FormGroup};
从'src/app/services/authentication.service'导入{AuthenticationService};
@组成部分({
选择器:“应用程序登录”,
templateUrl:'./login.component.html',
样式URL:['./login.component.css']
})
导出类LoginComponent实现OnInit{
构造函数(私有authenticationService:authenticationService){}
loginForm=新表单组({
电子邮件:new FormControl(“”),
密码:new FormControl(“”),
});
恩戈尼尼特(){
}
//当登录表单提交时调用
onSubmit(){
this.login();
}
login():void{
这是authenticationService
.login(this.loginForm.controls.email.value,this.loginForm.controls.password.value)
.订阅(//{
控制台日志(res);
});
}
}
阅读更多关于