4

I'm creating Angular2 application using angular-cli bootstrapper and use webpack-dev-server for debugging purposes.

For some kinds of http request I want to redirect them to another backend using webpack-dev-server proxy support.

For this reason I've created proxy.conf.json file:

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

And map angular cli to use this config file:

ng serve --proxy-config proxy.conf.json

After starting console message notifies me that proxy created successfully:

NG Live Development Server is running on http://localhost:4200

Proxy created: /api/** -> http://localhost:4201

But all request from http://localhost:4200/api/users always returns with 404 status code. I tried many examples of mapping urls but nothing helps:

"/api/users" -> "http://localhost:4201/users"
"/api/" -> "http://localhost:4201/"

Data from my proxied server are requesting successfully. What I am doing wrong?

4
  • you created file called proxy.config.json but you run ng serve with proxy.conf.json. I renamed the file to proxy.conf.json and pointed to google.com instead of localhost:4201 and it works for me. So config is fine. Commented Jan 5, 2017 at 15:58
  • Just misspelling. I've rectified it. But still not work ( Commented Jan 5, 2017 at 16:14
  • try to change localhost:4201 to google.com in your config Commented Jan 5, 2017 at 16:18
  • Changed to google.com and still no luck. I'm receiving 404 in google also. How to inspect in angular-cli generated project proxy log? Strange about 404 Commented Jan 5, 2017 at 20:12

1 Answer 1

11

I found solution. I've created simple express server to log all requests transferred from proxy server to inspect how mapping works. And I found out that I had wrong understanding about mapping.

Instead of strict mapping defined in config file:

/api/users => http://localhost:4201/users

webpack proxy server map using next rule:

/api/users => http://localhost:4201/users/api/users

So solution here is to add pathRewrite parameter to exclude prefix

{
  "/api/users": {
    "target": "http://localhost:4201",
    "secure": false,
    "pathRewrite": {"^/api" : ""}
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for explain us the way you fixed your issue ! You saved my day, I was exactly in the same case! Works perfectly!
@VadimB hi i am having similar kind of problem after doing these fix also its showing net::ERR_CONNECTION_REFUSED
Maybe some issues with target endpoint. Could you share your config?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.