使用Node.js和Express搭建图片缓存服务或应用服务器

使用Node.js和Express生成缩略图:
复制代码
const express = require('express');
const sharp = require('sharp');
const app = express();
const port = 3000;
 
app.get('/thumbnail/:filename', async (req, res) => {
    const filename = req.params.filename;
    const imagePath = `/path/to/images/${filename}`;
    sharp(imagePath)
        .resize(100, 100) // 设置缩略图尺寸
        .toBuffer()
        .then(data => {
            res.type('jpeg'); // 根据需要设置正确的MIME类型
            res.send(data);
        })
        .catch(err => {
            console.error(err);
            res.status(500).send('Error generating thumbnail');
        });
});
 
app.listen(port, () => {
    console.log(`Thumbnail server running at http://localhost:${port}`);
});

配置nginx反向代理

复制代码
location /thumbnail/ {
    proxy_pass http://localhost:3000/; # Node.js应用地址
    proxy_set_header Host $host; # 传递主机头信息到后端服务器
    proxy_set_header X-Real-IP $remote_addr; # 传递客户端IP地址到后端服务器
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 传递X
}
相关推荐
先吃饱再说3 小时前
从“地狱”到“楼梯”再到“同步写法”:Node.js 异步的二十年与Node内置fs模块详解
node.js
知识收割者3 小时前
Nodejs也能写Agent - 10.LangChain篇 - 初识LangChain
node.js
HjhIron5 小时前
Node.js 内置模块之 path 与 fs:从路径拼接到异步演进
node.js·promise
触底反弹5 小时前
🚀 Node.js path 和 fs 模块,从回调地狱到 async/await 的进化之路!
javascript·后端·node.js
sugar__salt6 小时前
Node.js path 与 fs 核心模块完全指南 —— 从路径处理到异步流程控制
javascript·node.js
屑曦晨6 小时前
npm 全局包迁移指南:从系统目录到用户目录
npm·node.js
moMo7 小时前
Node.js 文件操作:path 路径与 fs 异步流程
node.js
拾年2757 小时前
Node.js 异步进化论:从 path 路径拼接到 fs 文件读取,我终于理解了回调地狱的救赎之路
前端·node.js
小粉粉hhh8 小时前
Node.js(五)——编写接口
前端·javascript·node.js
先吃饱再说16 小时前
别再手动拼接路径了!Node.js path 模块的 9 个核心 API 详解
node.js