【问题标题】:Not able to call node service from angular无法从角度调用节点服务
【发布时间】:2020-12-11 15:12:48
【问题描述】:

我正在学习从角度调用节点,在我的组件中我有以下代码

import { Component, OnInit } from '@angular/core';
import {GetvalidationService} from '../_services/getvalidation.service';
@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {

  constructor(private service:GetvalidationService) { }

  ngOnInit(): void {
    this.getStudentData();
  }
  studentDetails :any =[]  
  getStudentData(){
        this.service.getStudentData().subscribe()
  }

}

服务定义如下

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class GetvalidationService {

  constructor(private http:HttpClient) { }

  authenticateLogin(userDetails){
   
    return this.http.post("/api/login",userDetails)
  }

  getStudentData(){
    return this.http.get("/api/student");
  }
}

并且我在 package.json 中也做了 proxy.conf.json 设置

我的 proxy.conf.json 看起来像

{
    "/api/*":{
        "target":"http://localhost:3000",
        "secure": false,
        "changeOrigin": true,
        "pathrewrite":{"^/api":""}
    }
}

尽管如此,当我调用学生时,角度服务会调用 http://localhost:4200/api/student 而不是端口 3000 上的节点服务,我哪里会出错?我使用 npm run start 来启动 Angular 应用程序

【问题讨论】:

  • 是什么让你认为它被重定向了?
  • 应该看到它在浏览器上调用 :4200,一旦 Webpack 开发服务器收到请求,代理就会发生。参见例如github.com/textbook/starter-kit/wiki/…(不是 Angular,但使用相同的代理)。是什么让您认为它不起作用
  • @jonrsharpe 因为在节点端我有 console.log 并且它没有写任何东西
  • getStudentData(){ this.service.getStudentData().subscribe((data)=>data) }
  • 请给minimal reproducible example - 后端是什么?你能成功地从另一个客户端(例如 curl)发出请求吗?您的路径重写似乎可疑。

标签: node.js angular


【解决方案1】:

你必须定义你的baseUrl,如果你不这样做,那么你最终会得到一个你在你的角度端口选项中定义的,即localhost:4200。

所以连接到节点所需的代码是这样的:

我建议将 api url 保留在环境中,以便您可以轻松地将其在不同的环境中移动,如下所示:

export const environment = {
  production: false,
  api: 'http://localhost:3000'
};

然后您的服务 ts 文件将包含来自 enviornment 的 api

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class GetvalidationService {


private baseUrl= environment.api + '/api';  // URL to your web api


  constructor(private http:HttpClient) { }

  authenticateLogin(userDetails){
   
    return this.http.post(`${this.baseUrl}/login`,userDetails)
  }

  getStudentData(){
    return this.http.get(`${this.baseUrl}/student`);
  }
}

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 2021-11-16
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2018-07-07
    • 1970-01-01
    相关资源
    最近更新 更多