angular-cli 启动angular2项目后的地址一般是http://localhost:4200
这里用的spring-boot的后台服务,本地端口是8080
*本例适用与当前时间 angular-cli最新版本
如果在anguar项目中直接写http://localhost:8080/api
会有跨域访问的错误,比如No 'Access-Control-Allow-Origin' header is present on the requested resource.
这样的错误
如果使用 jsonp
跨域资源共享服务可以解决这样的问题,但是显然这不是我们想要的解决办法。
angular 官方教程中的 in momery api
是在开发时期调试用的内存api。
这里找到的链接8080
后端服务接口的方法是:
修改 ng serve
的启动项
新建一个配置json文本 xxx.config.json(在项目的根目录下 )
{
"/api": {
"target": "http://localhost:8080",
"secure": "false"
}
}
注意 这里的 /api
就是你需要代理的api地址,举例你想代理/user
的api这里就应该配置为 user
在启动时执行 ng serve --proxy xxx.config.json
这时
this.http.get('/user').map(res => res.json().data as User[]).subscribe(/* ... */);
就会访问 http://localhost:8080/user
获取数据结果。
这里是angular-cli 官方 issue回答:
https://github.com/angular/angular-cli/pull/1896
https://github.com/angular/angular-cli/wiki/stories-proxy