webpack-dev-server and express on the same port?

Viewed 1180

I have cross domain issues in development environment with webpack-dev-server running on port 8080 while express backend running on port 5000.

  1. Backend api method calls through AJAX raise CORS errors
  2. Clicking on link that points to backend api does not pass session data

These problems are solvable, but I wonder why bother if they are not going to happen in production (where both client and backend will use same port)

Can this problem be solved (e.g. by running dev server and express on the same port or any other way?)

1 Answers

This is what worked for me: https://medium.com/@spencerfeng/setup-a-proxy-for-api-calls-for-your-angular-cli-app-6566c02a8

I feel like most people haven't ejected their webpack config... if you don't know what that means, then you've probably not ejected your webpack config so look under the option for "not been ejected" option.

I will note that if you're using ng serve instead of npm start you will either need to make the switch to npm start or type out that full command ng serve --proxy-config proxy.conf.json in order for this to work.

Additionally in your proxy.conf.json:

  • sample only shows '/api'
  • but if you've any other endpoints that don't start with /api, you will need to add them as well. Just in case you didn't realize that the '/api' was a path recognition string and not just a "setting".

example proxy.conf.json:

{
     "/api": { 
       "target": "http://localhost:3001",
       "secure": false
     },
     "/oauth": {
       "target": "http://localhost:3001",
       "secure": false
     },
     "/foo": {
       "target": "http://localhost:3002",
       "secure": false
     }
}
Related