Skip to content

Instantly share code, notes, and snippets.

@Markvandersteen
Created October 15, 2020 08:19
Show Gist options
  • Save Markvandersteen/d199e5ad5242b3206f917b4901b675da to your computer and use it in GitHub Desktop.
Save Markvandersteen/d199e5ad5242b3206f917b4901b675da to your computer and use it in GitHub Desktop.
import { NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import axios, { AxiosRequestConfig } from 'axios';
export class ReverseProxyMiddleware implements NestMiddleware {
after(str, substr): string {
return str.slice(str.indexOf(substr) + substr.length, str.length);
}
use(req: Request, res: Response, next: NextFunction) {
if (process.env.NODE_ENV != 'dev' || !process.env.PROXY) {
return next();
}
const url = `${process.env.PROXY}${this.after(req.originalUrl, '/src')}`;
const config = {
headers: req.headers,
method: req.method,
url: url,
} as AxiosRequestConfig;
if (req.method === 'POST') {
Object.assign(config, { data: JSON.stringify(req.body) });
}
axios(config).then(response => res.send(response.data));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment