【问题标题】:proxy configuration file not read代理配置文件未读取
【发布时间】:2019-11-07 16:16:58
【问题描述】:

我的开发环境 Angular 服务器在 localhost:4200 上运行,Spring Boot 服务器在 localhost:8080 上运行。 Angular 服务使用

调用 rest api 调用
this.http.get(window.location.protocol + '//' + window.location.hostname + ':8080/' +'<context-path>/api/<endpoint>');

代理配置文件:

{
    "/api": {
    "target": "http://localhost:800/",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": false
    }
}

我正在使用

启动我的服务器
ng serve --proxy-config proxy.conf.json

我故意提供端口号为 800,但我仍然可以从服务器获取结果。这确保我没有读取代理配置文件。

当我们可以直接从 Angular 服务访问 url 时,为什么需要代理配置文件?

【问题讨论】:

    标签: angular rest


    【解决方案1】:

    代理文件的使用基本上是告诉 Angular 检查请求的 url,如果匹配则将其替换为目标。
    在你的情况下,尝试请求this.http.get('api/something'),你会看到有一个指向http://localhost:800的重定向。

    回答你的最后一个问题:
    直接从 Angular 服务访问 url 对于本地开发来说似乎很方便。但是,一旦您将后端设置在与前端应用不同的服务器上,就可以节省大量时间来尝试找出出现 CORS 错误的原因。

    【讨论】:

    • 我可以看到 url 在角度控制台上重定向到 localhost:800 在控制台上引发错误。在代理配置文件中将 url 更改为localhost:8080 后,我可以在角度控制台上看到[HPM] /api/&lt;end-point&gt; -&gt; http://localhost:8080/。请求未命中服务器,在 chrome 开发工具上,我可以看到错误:Http failure response for http://localhost:4200/api/&lt;end-point&gt;: 404 Not Found" name: "HttpErrorResponse" ok: false status: 404 statusText: "Not Found" url: "http://localhost:4200/api/&lt;endpoint&gt;"
    猜你喜欢
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多