基于Node.js构建API从MongoDB关联路径提供商品图片服务
解决方案:创建图片读取API解决邮件模板图片显示问题
1. 后端API实现(以Express为例)
创建一个GET接口,接收图片文件名作为“图片ID”,从本地文件系统读取对应图片并返回正确响应头:
const express = require('express'); const fs = require('fs'); const path = require('path'); const app = express(); // 图片读取API app.get('/api/images/:imageId', (req, res) => { const imageId = req.params.imageId; // 拼接图片存储完整路径(根据你的实际存储目录调整) const imagePath = path.join(__dirname, 'images', imageId); // 根据文件扩展名设置对应Content-Type const ext = path.extname(imagePath).toLowerCase(); let contentType = 'image/jpeg'; if (ext === '.png') contentType = 'image/png'; else if (ext === '.webp') contentType = 'image/webp'; else if (ext === '.gif') contentType = 'image/gif'; // 读取并返回图片 fs.readFile(imagePath, (err, data) => { if (err) { res.status(404).send('图片不存在'); return; } res.set('Content-Type', contentType); res.send(data); }); }); // 服务启动 app.listen(process.env.PORT || 3000, () => { console.log('服务已启动'); });
2. 修改EJS模板中的图片引用
将原直接拼接相对路径的方式,改为调用新API接口,从商品images数组中提取文件名作为ID拼接到API路径:
<tr> <td> <img class="product-image" src="<%= serverLink + '/api/images/' + order.products[i].product.images[0].split('/')[1] %>" alt="<%= order.products[i].product.productName %>"> <%= serverLink + '/api/images/' + order.products[i].product.images[0].split('/')[1] %> <%= order.products[i].product.productName %> </td> <td> <%= order.products[i].productQuantity %> </td> <td>$<%= order.products[i].product.price * order.products[i].productQuantity %> </td> <!-- <td> <%= order.requests[i] ? order.requests[i].requestQuantity : '-' %> </td> --> </tr> <% } %>
3. 部署注意事项
- 部署时确保
images目录与服务代码的相对路径正确,或使用环境变量配置绝对存储路径 - 确认服务器权限允许Node.js读取
images目录下的文件 - 若使用云服务部署,需注意图片文件是否需纳入版本控制,或改用云存储替代本地存储避免文件丢失
内容的提问来源于stack exchange,提问作者Yeasir Hossain
相关产品推荐
相关产品推荐

