[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

 

posted @   Zhentiw  阅读(239)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-03-13 [Ramda] Convert a Promise.all Result to an Object with Ramda's zip and zipObj
2016-03-13 [RxJS] Basic DOM Rendering with Subscribe
2016-03-13 [RxJS] Resubscribing to a Stream with Repeat
点击右上角即可分享
微信分享提示