【发布时间】: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)发出请求吗?您的路径重写似乎可疑。