proxy-middleware: just pass a string

This commit is contained in:
Girish Ramakrishnan
2024-07-30 12:04:35 +02:00
parent 5aa0c57a74
commit a5249102f2
3 changed files with 16 additions and 43 deletions

View File

@@ -1,33 +1,26 @@
'use strict';
// https://github.com/cloudron-io/node-proxy-middleware
// MIT license
// contains https://github.com/gonzalocasas/node-proxy-middleware/pull/59
const { request } = require('http');
module.exports = function proxyMiddleware(options) {
//enable ability to quickly pass a url for shorthand setup
if(typeof options === 'string'){
options = require('url').parse(options);
}
function slashJoin(p1, p2) {
var trailing_slash = false;
options = options || {};
options.pathname = options.pathname || '/';
if (p1.length && p1[p1.length - 1] === '/') { trailing_slash = true; }
if (trailing_slash && p2.length && p2[0] === '/') {p2 = p2.substring(1); }
return p1 + p2;
}
module.exports = function proxyMiddleware(targetUrl) {
const options = require('url').parse(targetUrl);
return function (req, resp, next) {
var url = req.url;
// You can pass the route within the options, as well
if (typeof options.route === 'string') {
if (url === options.route) {
url = '';
} else if (url.slice(0, options.route.length) === options.route) {
url = url.slice(options.route.length);
} else {
return next();
}
}
//options for this request
var opts = Object.assign({}, options);
const { url } = req;
const opts = Object.assign({}, options);
if (url && url.charAt(0) === '?') { // prevent /api/resource/?offset=0
if (options.pathname.length > 1 && options.pathname.charAt(options.pathname.length - 1) === '/') {
opts.path = options.pathname.substring(0, options.pathname.length - 1) + url;
@@ -44,14 +37,6 @@ module.exports = function proxyMiddleware(options) {
delete opts.headers.host;
var myReq = request(opts, function (myRes) {
var statusCode = myRes.statusCode
, headers = myRes.headers
, location = headers.location;
// Fix the location
if (((statusCode > 300 && statusCode < 304) || statusCode === 201) && location && location.indexOf(options.href) > -1) {
// absoulte path
headers.location = location.replace(options.href, slashJoin('/', slashJoin((options.route || ''), '')));
}
resp.writeHead(myRes.statusCode, myRes.headers);
myRes.on('error', function (err) {
next(err);
@@ -71,12 +56,3 @@ module.exports = function proxyMiddleware(options) {
}
};
};
function slashJoin(p1, p2) {
var trailing_slash = false;
if (p1.length && p1[p1.length - 1] === '/') { trailing_slash = true; }
if (trailing_slash && p2.length && p2[0] === '/') {p2 = p2.substring(1); }
return p1 + p2;
}