There is a rewrite module. And when they are used with another proxy module in the middleware, they work together as a reverse proxy.
I use them when developing Single Pages Applications in my local field (so I don't need to configure apache / nginx locally)
This is to avoid CORS and send all pages (except js / css / images) to index.html for SPA to work.
var connect = require('connect'); var modRewrite = require('connect-modrewrite'); var proxy = require('proxy-middleware'); var url = require('url'); var app = connect() .use(modRewrite([ "^\/api\/(.*) /send-to-api/api/$1 [L]", "^(.*)\/css\/(.*) /send-to-ui/css/$2 [L]", "^(.*)\/js\/(.*) /send-to-ui/js/$2 [L]", "^(.*)\/images\/(.*) /send-to-ui/images/$2 [L]", "^(.*)\/fonts\/(.*) /send-to-ui/fonts/$2 [L]", "^(.*) /send-to-ui/index.html [L]" ])) .use('/send-to-api', proxy(url.parse('http://api.server.dev/'))) // Don't forget the last backslash .use('/send-to-ui', proxy(url.parse('http://ui.server.dev/' ))) // Don't forget the last backslash .listen(9000)
Make sure I use the [L] flag because I want it to rewrite and skip the rest of the rules.
In this case, only the /api tags receive the proxy server to api.server.dev , the rest - ui.server.dev . The url /send-to-api and /send-to-ui prefixes are temporary, and I use them to distinguish what comes next, it is removed by connect before being sent to the corresponding servers.
And yes, if redirected, proxy-middleware will change the Location header to localhost:9000
David Rz Ayala
source share