Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import { IncomingMessage } from "http";
import proxyMiddleware from "http-proxy-middleware";
import { parse } from "url";
import { logger } from "../server/logger";
export const UpdateProxy = proxyMiddleware({
target: "Ship Cloud Binary - Update",
proxyTimeout: 5000,
router(req: IncomingMessage): string {
if (!req.url) {
throw new Error("Invalid URL");
}
const { pathname = "" } = parse(req.url);
const splitPath = pathname.split("/");
const [, , , , updateId] = splitPath;
// tslint:disable-next-line:no-http-string
const shipUpdateInstanceHost = `http://shipupdate-${updateId}.shipupdate-${updateId}.svc.cluster.local:8800`;
return shipUpdateInstanceHost;
},
pathRewrite(path: string): string {
export function createProxyHandler(options: ProxyOptions, logging: boolean) {
const route = options.route.charAt(0) === '/' ? options.route : '/' + options.route;
const proxyHostname = options.hostname || 'localhost';
return proxy({
// TODO: how do we detect https?
target: `http://${proxyHostname}:${options.port}`,
pathRewrite: {
[`^${route}`]: `/`,
},
logLevel: logging ? 'info' : 'silent',
});
}
next()
})
// Yes I just copied most of this from react-scripts ¯\_(ツ)_/¯
app.use(publicPath,
historyApiFallback({
index: '/200.html',
disableDotRule: true,
htmlAcceptHeaders: ['text/html'],
}),
express.static(baseDir, { index: '200.html' })
)
if (proxy) {
if (typeof proxy !== "string") throw new Error("Only string proxies are implemented currently.")
app.use(httpProxyMiddleware({
target: proxy,
onProxyReq: proxyReq => {
if (proxyReq.getHeader('origin')) proxyReq.setHeader('origin', proxy)
},
changeOrigin: true,
xfwd: true,
}))
}
this.start = this.start.bind(this, app, port)
}
const middleware: (MiddlewareHandler | PerRouteMiddleware)[] = [
webpackDevMiddleware(compiler, {
publicPath: app.publicPath,
stats: {colors: true},
}),
webpackHotMiddleware(compiler),
compression(),
...middlewares,
];
if (serverEnabled) {
middleware.push(
proxyMiddleware(['**', '!**/*.*'], {
target: `http://localhost:${app.serverPort}`,
}),
);
} else {
middleware.push(
function (req: IncomingMessage, res: ServerResponse, next: () => void) {
if (req.url && !/\.[a-zA-Z0-9]+$/.test(req.url)) {
req.url = '/index.html';
}
return next();
},
);
}
return Promise.resolve({
port: app.port,
contentBase: '',
proxy: {
'**': {
target: `http://localhost:${pythonPort}`,
},
},
stats: {
colors: true,
},
})
);
app.use(hotMiddleware(compiler));
app.use(
proxyMiddleware(['**'], {
target: `http://localhost:${pythonPort}`,
logLevel: 'error',
})
);
app.listen(port, err => {
if (err) {
console.error(err);
}
console.log(`Listening at http://localhost:${port}/`);
});
configure.forEach(proxyConfig => {
const bypass = typeof proxyConfig.bypass === 'function';
const context = proxyConfig.context || proxyConfig.path;
const proxyMiddleware = httpProxyMiddleware(context, proxyConfig);
app.use((req, res, next) => {
const bypassUrl = bypass && proxyConfig.bypass(req, res, proxyConfig) || false;
if (bypassUrl) {
req.url = bypassUrl;
next();
} else if (proxyMiddleware) {
return proxyMiddleware(req, res, next);
}
});
});
};
timings: false,
chunks: false,
chunkModules: false,
modules: false,
children: false,
version: false,
cached: false,
cachedAssets: false,
reasons: false,
source: false,
errorDetails: false
}
}));
app.use(webpackHotMiddleware(compiler));
app.use('/v1', proxy({
target: 'http://cangdu.org:8001',
changeOrigin: true
}));
app.use('/json', proxy({
target: 'http://60.205.213.209:8080',
changeOrigin: true
}));
app.get('*', (req, res, next) => {
const filename = path.join(compiler.outputPath, 'index.html');
compiler.outputFileSystem.readFile(filename, (error, result) => {
if (error) {
next(error);
} else {
res.set('content-type', 'text/html');
const HOST = HELPER.findArg('host') || '127.0.0.1';
const devURL = `http://${HOST}:${PORT}`;
const urlParts = url.parse(devURL);
const app = express();
//gzip
app.use(compression());
app.use(require('./middleware/output'));
CONFIG.static_dir.map((item) => {
app.use(`/${item}`, express.static(path.join('build', item)));
});
app.use('/iot', proxy({
target: 'http://10.109.0.59:10000',
changeOrigin: true
}));
mockMiddleware(app);
app.use('*', (req, res, next) => {
fs.readFile('./build/index.html', (err, data) => {
if (err) {
next(err);
} else {
res.set('content-type', 'text/html');
res.send(data);
res.end();
}
});
const parsedUrl = url.parse(target);
const realTarget = [parsedUrl.protocol, parsedUrl.host].join('//');
const targetPath = parsedUrl.path;
const pathRewrite = (path, req) => {
let matchPath = req.originalUrl;
const matches = matchPath.match(pathPattern);
if (matches.length > 1) {
matchPath = matches[1];
}
return path.replace(req.originalUrl.replace(matchPath, ''), targetPath);
};
return proxy(filter, { target: realTarget, pathRewrite });
}
export const app = express();
app.get('/', (req, res) => res.json({ message: 'Hello Web Myna' }));
for (const api of config.apis) {
const proxyOptions = {
changeOrigin: true,
proxyTimeout: 5000,
timeout: 5000,
target: api.url,
ignorePath: false,
pathRewrite: path => path.replace(`/${api.name}`, ''),
onProxyReq: proxyReq =>
proxyReq.setHeader(`${api.tokenKey || 'authorization'}`, `${api.tokenPrefix || 'Bearer'} ${api.token}`),
};
app.use(`/${api.name}`, myna(api), proxy(proxyOptions));
}