【问题标题】:Proxy setup in angular cliangular cli中的代理设置
【发布时间】:2020-03-10 03:02:23
【问题描述】:

我有proxy.conf.json

{
"/api/*": {
    "target": "https://api.dev.xyz.com",
    "secure": false,
    "changeOrigin": true,
    "pathRewrite": { "^/api": "" },
    "logLevel": "debug"
  }
}

我在package.json 文件中有ng serve --proxy-config proxy.conf.json。当我使用npm start 运行我的项目时,它显示错误

ng serve --proxy-config proxy.conf.json
Browserslist: caniuse-lite is outdated. Please run next command `npm update`
10% building 3/3 modules 0 active[HPM] Proxy created: /api  ->  https://api.dev.xyz.com
[HPM] Proxy rewrite rule created: "^/api" ~> ""
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]

我已经检查了多个堆栈溢出答案reference link,但我仍然被困在这里很长时间了。

【问题讨论】:

  • 您在哪里看到错误?除了 caniuse-lite 包,没有错误。它告诉您重写规则已被应用(这意味着当您发出像http.get<any>('/api/something') 这样的http 请求时,它会将/api/something 替换为https://api.dev.xyz.com/something
  • 错误到底在哪里?
  • 我有像 https://api.dev.xyz.com/api/login 这样的 API 调用,当我尝试点击静止时它显示 blocked by cors error in the browser console
  • 如何创建请求?是this.http.get('https://api.dev.xyz.com/api/login') 还是this.http.get('/api/login')(甚至this.http.get('/api/api/login'),给定代理文件中的路径重写)?
  • 我正在以this.http.get('https://api.dev.xyz.com/api/login')的身份创建请求

标签: angular proxy angular-cli


【解决方案1】:

好的。在询问更多信息后(请参阅问题上的 cmets),这是一个答案:

代理文件正在做的是创建一个重写规则。这意味着无论您在何处创建对/api/something/ 的请求,它都会被重写为https://api.dev.xyz.com/something,并且在某种程度上被视为来自完整的url(因此没有CORS 错误)。

尝试使用this.http.get('/api/something') 进行请求,您将在控制台中看到一条消息,告诉您请求已被重写。

【讨论】:

  • 如果我将请求 URL 从 https://api.dev.xyz.com/something 更改为 /api/something。它击中localhost:4200/api/something 而不是https://api.dev.xyz.com/api/something
  • 即使在 Angular cli 中它也显示来自"/api/students?page=1&page_size=20&paginate=true" to "/students?page=1&page_size=20&paginate=true" 的重写路径。
  • GET /api/students?page=1&page_size=20&paginate=true ~> https://api.dev.xyz.com
猜你喜欢
  • 2018-03-21
  • 2018-01-23
  • 1970-01-01
  • 2017-07-09
  • 1970-01-01
  • 2017-04-21
  • 2018-06-01
  • 2018-04-12
  • 2017-07-28
相关资源
最近更新 更多