【问题标题】:request url problems when using base href使用基本 href 时的请求 url 问题
【发布时间】:2017-01-26 19:26:34
【问题描述】:

快速版本 - 我相信我想要的: 如何配置angular2 http 服务以忽略<base href>

更长的版本 - 如果有更好的方法: 在我的项目中,我们使用 Apache 为两个 Angular 应用程序提供服务:

http://host/index.html - angular 1
http://host/ng2/index.html - angular 2

它们都使用相同的端点

http://host/api/foo

两个应用都使用同一个虚拟主机。 angular 2 应用位于磁盘上的 public/ng2 下。

问题归结为:

当我使用:<base href="/ng2/"> 时,角度应用程序加载正常。 但是所有使用 http 服务的 api 请求都会被污染。

http.get('/api/foo/2') goes to http://host/ng2/api/foo

我目前的解决方案是将base href 设置为<base href="/">,并将除index.html 之外的所有angular2 文件直接放在/public 下。 (index.html 仍在 /public/ng2 中)这可行,但它是一团糟。

我想要什么:

  • 所有 angular2 文件都在 /public/ng2 中(由于 <base href="/ng2/"> 或其他 Apache 配置而有效)
  • 传出请求没有附加 ng2。

不能硬编码网址

【问题讨论】:

  • 我建议使用 $config 变量,其中包含用于 HTTP 调用的 API 的完整基本 URL,并像这样使用 http:http.get(api_root + '/foo/2')
  • 感谢@KiJéy。我忘了提到的是我们部署了多个实例。每个都有自己的 /api/foo/2。例如。 (customer1-host/api/foocustomer2-host/api/foo)。所以相对路径会好很多。
  • 您能解释一下为什么您认为相对路径会更好吗?我同意@KiJéy,将 URL 放入环境文件并使用绝对路径。
  • 我上面描述的问题肯定可以使用绝对路径来解决。当我写这个问题时,我从未认真考虑过以编程方式创建绝对路径的选项。例如 fullUrl = document.location.protocol + "//" + document.location.host + "/" + relativeUrl。这种方法确实有效 - 谢谢!

标签: apache angular angular-cli


【解决方案1】:

最后,我按照 Ki Jey 的建议做了,并使用绝对 URL 来访问 API。

service.base.ts: 
protected getAbsoluteUrl(relativeUrl : String) : String { 
  return document.location.protocol + "//" + document.location.host + "/" + relativeUrl
}

service.ts:
class service extends BaseService
  getTheFoo(){ 
    http.get(this.getAbsoluteUrl(foo/2))...
  }

【讨论】:

    【解决方案2】:

    只需将 '/' 附加到 api 调用将停止附加 baseHref 值。

      getFoo(): Observable<any> {
        const url = '/' + 'api/foo';
        return this.http.get<any>(url);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-28
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      相关资源
      最近更新 更多