后端的 Angular-CLI 代理不起作用

标签 angular proxy angular-cli

https://github.com/angular/angular-cli#proxy-to-backend这是如何代理到后端的说明。我一步一步地做了所有事情,但仍然没有代理请求。

8080 - 我的 Express 后端 4200 - 我的 Angular2 前端

在 Angular2 项目中我有文件 proxy.conf.json内容如下:

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

在 Angular2 package.json 中,我更改了 start程序 "start": "ng serve --proxy-config proxy.conf.json"

当我在里面输入 commander npm start然后在开始时我可以看到 Proxy created: /api -> http://localhost:8080 .好吧,我想到目前为止还不错。

我正在尝试发送请求 (Angular2)

  constructor(private http: Http) {
    this.getAnswer();
  }

  getAnswer(): any {
    return this.http.get("/api/hello")
      .subscribe(response => {
        console.log(response);
      })
  }

我收到一个错误 http://localhost:4200/api/hello 404 (Not Found) .正如我们所见,没有任何东西被代理。为什么?我做错了什么吗?

要清楚。当我手动转到 http://localhost:8080/hello 时,一切正常。在后端没有什么可寻找的。

最佳答案

你能试试这个吗:

{
  "/api": {
    "target": "http://url.com",
    "secure": false,
    "pathRewrite": {"^/api" : ""}
  }
}

对我有用,

** NG Live Development Server is running on http://localhost:4200. **
 10% building modules 3/3 modules 0 active[HPM] Proxy created: /api  ->  http://ec2-xx-xx-xx-xx.ap-south-1.compute.amazonaws.com
[HPM] Proxy rewrite rule created: "^/api" ~> ""

关于后端的 Angular-CLI 代理不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809008/

相关文章:

java - 如何在 Java 中使用 HTTP 代理

node.js - Angular 5 Electron-Packager在 'npm prune --production'失败

Angular Testing 失败,无法在 'send' 上执行 'XMLHttpRequest'

angular - angular-cli 如何与 ES6 模块一起工作?

angular - RxJS 5 - 最后,最终确定,完成,没有任何效果

javascript - 为 getter 提供默认值,而不会导致 Angular 2 模型类中的堆栈溢出

json - Angular 2 : Access object data

html - Angular 2 Material 自定义 md-menu

java - 编码java代理

http - HTTP 中介的请求处理模型