当我导入HttpClient
来调用我自己编写的node.js API时,URL的设置存在一些问题。
例如:
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class myComponent implements OnInit {
constructor(
private http: HttpClient,
) {}
ngOnInit(): void {
this.http.get('http://127.0.0.1:3000/getData/theme').subscribe(data => {
});
});
}
//angular default port 4200,
//node.js default port 3000,
当我设置 this.http.get('/getData/theme')
时,get
方法将调用 http://127.0.0.1:4200
,这是错误的。如果我设置 this.http.get('http://127.0.0.1:3000/getData/theme')
进行本地开发,则可以正常运行。但是,在使用 ng build
部署到实际服务器后,它无法正确连接。
控制台输出如下:
GET http://127.0.0.1:3000/getData/theme
net::ERR_CONNECTION_REFUSED
GET http://localhost:3000/structureData/themeData
net::ERR_CONNECTION_REFUSED
如何设置正确的URL以实现在线和本地开发状态的兼容?
angular-cli服务器-如何将API请求代理到另一个服务器? 我设置了package.json:
"start": "ng serve --proxy-config proxy.conf.json"
并且
proxy.conf.json
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
无法运行:
this.http.get('/getData/theme')
GET http://localhost:4200/getData/theme 404 (Not Found)
or
this.http.get('/api/getData/theme')
GET http://localhost:4200/api/getData/theme 404 (Not Found)