【问题标题】:Angular with https-proxy-agent only works with trailing / - what am I missing?带有 https-proxy-agent 的 Angular 仅适用于尾随 / - 我错过了什么?
【发布时间】:2022-01-15 01:56:13
【问题描述】:

我用 ngx-rocket 创建了一个 Angular 项目。

  • 在 localhost:4200 运行的 Angular 前端
  • 后端在 locahlost:8000 提供 api

我使用预配置的 https-proxy-agent 和 ngx-rocket 将我的 api 请求从我的前端重定向到我的后端。 我曾经有我的 api 端点 localhost:8000/api/endpoint 并且以前可以工作,但现在切换后端以在 localhost:8000/endpoint 上收听。我调整了代理以反映这些更改,但由于某些原因,现在它仅在我请求带有斜杠的 localhost:4200/endpoint/ 时才有效,而之前没有。

我可以只更改前端中的端点,但我更愿意了解正在发生的事情并解决根本问题。

proxy.conf.js

const proxyConfig = [
  {
    context: '/api/*',
    pathRewrite: { '^/api': '' },
    target: 'http://localhost:8000/',
    changeOrigin: true,
    secure: false,
    logLevel: 'debug'
  }
];

环境.ts


export const environment = {
  production: false,
  version: env.npm_package_version + '-dev',
  serverUrl: '/api/',
  defaultLanguage: 'de-DE',
  supportedLanguages: ['de-DE', 'en-US'],
};

示例服务:

  private endpointUrl = 'endpoint';


  getEndpointList(): Observable<Endpoint[]> {
    return this.http
      .get<ApiResponse<Endpoint>>(this.endpointUrl)
  };

此端点不起作用,但它曾经使用旧配置。如果我将其更改为 private endpointUrl = 'endpoint/'; 它恰好可以工作。

当前行为:

请求http://localhost:4200/api/endpoint

  • 角度控制台中没有代理日志

网络(Chrome 开发工具):

  • 状态码:301
  • 位置:/endpoint/
  • 产生的请求:http://localhost:4200/endpoint/

请求http://localhost:4200/api/endpoint/

  • [HPM] Rewriting path from "/api/endpoint/" to "/endpoint/"
  • [HPM] GET /api/endpoint/ ~&gt; http://localhost:8000/

网络(Chrome 开发工具):

  • 状态码:200
  • 位置:/endpoint/
  • 返回 api 响应

预期行为:

api 请求应该在没有尾部斜杠的情况下工作。恐怕这很愚蠢,但我目前无法弄清楚,所以任何帮助都会非常感激。

【问题讨论】:

    标签: django angular api proxy https-proxy-agent


    【解决方案1】:

    我现在解决了。

    我使用带有 Django REST 框架的 django 作为后端,它使用带有斜杠的 url 作为默认值。当我在浏览器中打开页面时,它也没有斜线,因为我被自动转发了。该转发在代理上不起作用,因为从 localhost:8000 发送的响应将位置设置为 /endpoint/,这总是导致 localhost:4200

    我通过删除 urls.py 中的尾部斜杠来修复它:

    router = routers.DefaultRouter(trailing_slash=False)
    

    此外,由于某种原因,我不得不删除我的浏览器数据。

    【讨论】:

      猜你喜欢
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多