2

I've just migrated my application to Angular CLI. I already have my REST API Node server up and running. I would like to be able to run my front-end with ng serve, to have the auto-reload feature every time I change a file, but also have it connect to my node back-end.

Livereload server is running on port 49152 Serving on port 4200 Node listening on port 8080

All my node routes are prefixed with api.

Is this possible?

grim_i_am
  • 3,664
  • 5
  • 19
  • 19
  • What precisely doesn't work? I've done this before with a tomcat server and no issues. I'm not sure how a node server would change anything. – Pace Aug 02 '16 at 20:20
  • Well, if my angular app is being served by the development server on port 4200, any back-end API requests will also be sent to port 4200. How could I have 2 servers listening to the same port? Theoretically I could change my services to call the back-end on a different port but that would be a pain, besides breaking the same origin policy. – grim_i_am Aug 03 '16 at 08:04
  • 1
    Ok, I see your problem now. Yes, in the past I used to solve this with the grunt server by setting up a proxy (the grunt server would proxy all requests that didn't match a front-end static resource). It looks like there is a [request](https://github.com/angular/angular-cli/issues/889) for such a feature in angular-cli but it hasn't been implemented yet. You may also look at [this question](http://stackoverflow.com/questions/37172928/angular-cli-server-how-to-proxy-api-requests-to-another-server). – Pace Aug 03 '16 at 17:52
  • I got some helpful pointers in the first link you mentioned. Thanks! – grim_i_am Aug 03 '16 at 21:36

1 Answers1

5

So because a formal answer hasn't been submitted for this, I'll give it a shot. Say you have your node powered api running on 8080. You can get that started in one terminal/cmd window with your typical node server.js command. Then, in the same project folder, the same one you have your package.json you will want to add a proxy-config.json file with the following content

{
    "/api": { // or whatever your endpoint is in your api routes
        "target": "http://localhost:8080", // your node server.js api
        "secure": false
    }
}

Then you can start your project with ng serve --proxy proxy-config.json.

Docs: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

gh0st
  • 1,653
  • 3
  • 27
  • 59
  • 1
    Superb solution @gh0st. I have been looking for this solution since 5 hours! Thanks a lot! :) – aareeph Nov 23 '19 at 14:05