[Node.js] Proxy Requests for Local and Remote Service Parity

High availability apps require that no distinction be made between local and remote services. Attached resources should be accessed by environment variables, and in doing so allow you to swap out one attached resource for another.

In this lesson we will setup a reverse proxy that directs image path requests and routes them through a defined server URL. By doing so, we decouple server requests for images which allows for easy switching from locally-served image assets to a CDN by simply updating an environment variable.

Install:
yarn add express-http-proxy
require('dotenv').config(); 

const path = require('path'); const express = require('express'); // require the lib const proxy = require('express-http-proxy'); // read base image url from the env variable const baseImageUrl = process.env.BASE_IMAGE_URL; // Setup proxy image url by cond const proxyBaseImageUrl = baseImageUrl // if the basImage url was given ? proxy(baseImageUrl, { proxyReqPathResolver: function (req) { // set image url from a remote server const newPath = baseImageUrl + req.path; console.log(newPath); return newPath; } }) : express.static(path.join(__dirname, 'public/images')); // fallback to local const app = express(); app.use('/images', proxyBaseImageUrl); app.listen(8080);

Create .env file:

BASE_IMAGE_URL= https://goo.xxxxxxxxxxxxxxxxxx
原文地址:https://www.cnblogs.com/Answer1215/p/8561876.html