【问题标题】:how to proxy API requests? (Angular-CLI)如何代理 API 请求? (角 CLI)
【发布时间】:2018-10-28 17:21:08
【问题描述】:

我正在使用 Spring-4 和 Angular-5 开发 Java 项目。会话在弹簧侧生成。

所以,我无法从 Angular 服务生成此会话。它在 Postman 上工作,我可以在 PostMan 中得到响应。 但它不适用于 Angular post 方法调用。

所以,我认为这可能是代理的问题。 (如果我错了,请纠正我)。

所以,我的本地网址是:- http://localhost:8080/MacromWeb/ws/login 那么,如何制作proxy.conf.json 文件?

因此,我已将此代码添加到我的 package.json 文件中,

"start": "ng serve --proxy-config proxy.conf.json",

我创建了一个名为proxy.conf.json 的新文件。 并将此代码放入其中。

{
  "/": {
    "target": "http://localhost:8080/MacromWeb/ws",
    "secure": false
  }
}

然后我尝试了 ng servenpm start 两者。

邮递员截图。

【问题讨论】:

  • 当您进行 http 调用时,您使用什么端点?

标签: spring angular spring-security angular5


【解决方案1】:

您可以通过代理来实现,您需要在代理配置中提供适当的值。

/* 也应该可以工作,但如果 MacromWeb 在 API URL 中很常见,那么请提供 / 而不是 /MacromWeb/*

proxy.conf.json 看起来像这样,

{
    "/MacromWeb/*": {
        "target": {
            "host": "localhost",
            "protocol": "http:",
            "port": 8080
        },
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug"
    }
}

希望对你有帮助。

【讨论】:

  • 哦。感谢您的快速答复。这是proxy.conf.json 的代码吗?
  • 是的,这是proxy.conf.json,虽然我建议你使用javascript文件proxy.conf.js,如果应用程序API调用是针对不同的API端点(或不同的服务器)
  • 我试过你的代码兄弟。它不工作。我必须将任何内容更改为 package.json 吗?我有一个问题,我正在使用此 url http://localhost:4200/#/pages/login 中的此服务,我正在调用此 url http://localhost:8080/MacromWeb/ws/login。那么它有效吗?
  • @Bhavin,你不应该像这样显式使用整个 URL -> http://localhost:8080/MacromWeb/ws/login 在进行 API 调用时,你应该使用这样的东西 -> this.http.get("MacromWeb/ws/login")
  • 基本路径也很重要,你在index.html中使用的基本路径是什么?
【解决方案2】:

假设我们有一个在 http://localhost:3000 上运行的服务器,我们希望所有对 http://localhost:4200/api 的调用都转到该服务器。

在我们的proxy.conf.json文件中,我们添加如下内容

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "pathRewrite": {
      "^/api": ""
    }
  }
}

更多信息:here

【讨论】:

    猜你喜欢
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2019-02-09
    相关资源
    最近更新 更多