【发布时间】:2018-08-20 17:49:07
【问题描述】:
当我导入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 server - how to proxy API requests to another server?
我设置了 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)
或
this.http.get('/api/getData/theme')
GET http://localhost:4200/api/getData/theme 404 (Not Found)
【问题讨论】:
-
查看建议的重复问题。如果您使用的是 cli,您可以使用代理配置,该配置将路由到您选择的主机(可以配置服务器和端口)。
-
@Igor 代理配置旨在通过 ng serve 运行开发服务器时代理调用。运行 ng build 后,您负责 Web 服务器及其配置。
-
它不起作用,我会在我的问题中修改。
-
"/api"是一种模式。任何以/api开头的 URL 都会通过代理进行路由。/getData不以/api开头。如果你想全部捕获,你可以使用一个空字符串。
标签: angular angular-cli