angular2的angular-cli如何使用代理api

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值