本文介绍了后端的 Angular-CLI 代理不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

https://github.com/angular/angular-cli#proxy-to-backend here is an instruction how to do proxying to backend. I did everything step by step and still requests aren't proxied.

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

8080 - my Express backend4200 - my Angular2 frontend

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

In Angular2 project I have file proxy.conf.json with content like this:

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

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

In Angular2 package.json I changed start procedure to "start": "ng serve --proxy-config proxy.conf.json"

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

When I type inside commander npm start then at the start I can see Proxy created: /api -> http://localhost:8080. Well, so far is good I guess.

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

I'm trying to send a request (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).正如我们所看到的,没有任何东西被代理.为什么?我做错了什么吗?

I'm getting an error that http://localhost:4200/api/hello 404 (Not Found). As we can see, nothing has been proxied. Why? Did I do something wrong?

说清楚.当我手动转到 http://localhost:8080/hello 时,一切正常.后端没什么可看的.

To be clear. When I go manually to http://localhost:8080/hello, all works fine. There is nothing to look for in backend side.

推荐答案

你可以试试这个:

{
  "/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 代理不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:37