关于angular:Angular7-http代理proxy配置

3次阅读

共计 654 个字符,预计需要花费 2 分钟才能阅读完成。

前后端拆散开发时,须要进行 http 申请后端,这时刚会遇上跨域问题。
解决办法之一就是应用 proxy 代理
ng proxy 是基于 webpack proxy, 更详尽阐明:https://webpack.js.org/config…

1. proxy.conf.json

在我的项目根目下增加文件:proxy.conf.json

示例:

{
    "/api": {
        "target": "http://localhost:8089/",
        "secure": false,
        "pathRewrite": {"^/api": ""},"changeOrigin": true,"loglevel":"debug"
    }
}

示例阐明:
对所有 /api/* 的申请,转发到 http://localhost:8089/

  • target,个别是后端服务地址
  • pathRewrite,重写 url 门路。成果就是前端对立申请后端时应用/api/,而理论代理时则无此关键字。
  • changeOrigin,如果你的后端服务不是localhost,则需把此项设为true
  • loglevel,日志级别。包含 debug, info, warn, error, and silent (默认 info)

2. 启动代理

ng cli 启动我的项目时会查看是否存在代理文件proxy.conf.json,所以可不需配置启动我的项目

$ ng serve

如果你新增了其余代理文件,也能够指定文件进行启动

$ ng serve --proxy-config proxy.conf.json

这就实现了代理后端的配置了,应用代理也解决了跨域拜访的问题。

正文完
 0