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.
We then need to tell the Angular CLI to use this proxy config. In angular.json, find the serve configuration of the architects section and add a new option to the options object called proxyConfig:
We can fix this by setting up the Angular CLI to proxy all requests to the API for us so they appear to be coming from the same origin. Check out this egghead video to learn more: To add the proxy, first create a file in the src folder of the Angular project called proxy.conf.json. Add the following configuration:
There are two ways to configure one is to add in the angular.json and another is adding a proxy-config flag to the start script. We can rewrite the path with the option pathRewrite. We can proxy multiple entries to one backend API with the proxy.config.js.
We need to make sure the Angular App and Backends are running on different ports for successful communication. There are two ways to configure one is to add in the angular.json and another is adding a proxy-config flag to the start script. We can rewrite the path with the option pathRewrite.
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" ~> ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With