2

I have a backend service running at http://localhost:9090/. All calls starting with /api/* should be forwarded to it, without the /api in front of it. So when I call http://localhost:8080/api/my/route it should proxy to http://localhost:9090/my/route.

If I use the following option:

proxy : [{
  path : '/api/*',
  target : 'http://localhost:9090'
}]

When calling http://localhost:8080/api/my/route, the backend service complains that it cannot find route /api/my/route.

The documentation suggests that I could use any options from node-http-proxy, but I can't figure out the correct options to use.

What options do I need to use to get the desired result?

Narigo
  • 2,979
  • 3
  • 20
  • 31

2 Answers2

10

As of webpack-dev-server version >= 1.15.0, you can use the documented pathRewrite:

proxy: {
  '/api': {
    target: 'https://other-server.example.com',
    pathRewrite: {'^/api' : ''}
  }
}
Aprillion
  • 21,510
  • 5
  • 55
  • 89
2

EDITED as for version <= 1.14.1 You can use the option 'rewrite'. this is a function that will be called for each request matching the pattern (eg: '/api/*'). the function must match the signature function (req,proxyoptions) { }

Like so :

proxy : [{
  path : '/api/*',
  target : 'http://localhost:9090',
  // bypass
  rewrite: function(req, options) {
    // manipulate req here 
    // in your case I think it's removing the /api part of url
  }
  // 
}]
Kristofen44
  • 118
  • 1
  • 10
  • Thanks a lot for this, it works! Is this documented somewhere in the webpack-dev-server docs? – Narigo Feb 19 '16 at 10:55
  • Great..I've found this by searching the code not found in docs. Warning ! After looking at the master version of webpack-dev-server's code on github [link](https://github.com/webpack/webpack-dev-server/blob/master/lib/Server.js) I think the 'rewrite' function will not be supported in next versions. I'll edit the answer with a sample using bypass function instead – Kristofen44 Feb 19 '16 at 11:58
  • I've added the `rewrite` to the [docs](https://github.com/webpack/docs/wiki/webpack-dev-server#rewriting-urls-of-proxy-request). As bypass already passes the response as an argument to the registered handler, I'm unsure how bypass should be able to modify the request. – Narigo Feb 19 '16 at 16:29
  • you're right... I've realized that 'bypass' will not help. I think 'bypass' can be usefull only if you want to totally bypass the proxy feature on specific pattern... – Kristofen44 Feb 19 '16 at 21:13
  • Looks like the rewrite option got replaced by the pathRewrite option - at least it got kicked out of the docs in favor of that. I'm accepting the answer by @Aprillion to help find the best answer for future problem solvers – Narigo Sep 23 '16 at 17:35