Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

Angular-CLI proxy to backend doesn't work

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 - my Express backend 4200 - my Angular2 frontend

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

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

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

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.

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);
      })
  }

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Could you try with this one:

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

It works for me,

** 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" ~> ""

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...