Created
March 12, 2020 06:52
-
-
Save exiguus/f68fc60e7693e9f39ba24446b6c3e951 to your computer and use it in GitHub Desktop.
express / proxy, middleware - manipulate and map target requests and responses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* express / proxy, middleware | |
* manipulate and map target requests and responses | |
* | |
* - inject assets to test / develop features, fixes ... | |
* - overwrite JavaScript and CSS served by the target | |
*/ | |
/** | |
* Module dependencies. | |
*/ | |
const express = require('express'); | |
const { | |
createProxyMiddleware | |
} = require('http-proxy-middleware'); | |
/** | |
* Configure proxy middleware | |
*/ | |
// context to serve from target | |
const context = [ | |
'/**', | |
'!/assets/backend/path/js/*.js', | |
'!/assets/backend/path/css/*.css', | |
]; | |
// options to serve target | |
const options = { | |
target: 'https://backend.local', | |
changeOrigin: true, // for vhosted sites, changes host header to match to target's host | |
secure: false, // if the target serve via https | |
logLevel: 'debug', | |
}; | |
// connect target | |
const backend = createProxyMiddleware(context, options); | |
// serve app | |
const app = express(); | |
/** | |
* Add the proxy to express | |
*/ | |
app.use('/', backend); | |
/** | |
* Manipulate request / response | |
*/ | |
// rewrite vendor|app css|js | |
app.use(function (req, res, next) { | |
// rewrite files | |
const re = /(vendor|app)\.[0-9]{12}\.(js|css)/; | |
if (req.url.match(re)) { | |
res.setHeader('x-middleware-rewrite', 'true'); | |
res.setHeader('x-middleware-rewrite-match', re); | |
res.setHeader('x-middleware-rewrite-origin', req.url); | |
// rewrite req.url from, to | |
req.url = req.url.replace(re, '$1\.min\.$2'); | |
res.setHeader('x-middleware-rewrite-status', 'done'); | |
} | |
next(); | |
}); | |
/** | |
* Add static assets | |
*/ | |
// backend path overwrite with static vendor|app css|js | |
app.use('/assets/backend/path/js/', express.static('dist/static/js')); | |
app.use('/assets/backend/path/css/', express.static('dist/static/css')); | |
app.listen(3000); | |
console.log('[DEMO] Server: listening on port 3000'); | |
console.log('[DEMO] Opening: http://localhost:3000/'); | |
require('open')('http://localhost:3000/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment