部署至Vercel后静态图片文件无法访问的问题排查
MERN应用Vercel部署静态图片加载问题解决方案
目录结构

现有配置文件
api/vercel.json
{ "version": 2, "builds": [ { "src": "./index.js", "use": "@vercel/node" } ], "routes": [ { "src": "/(.*)", "dest": "/" }, { "src": "/images/(.*)", "dest": "/" } ] }
api/index.js
const __dirname = path.resolve(); app.use( "/images/products", express.static(path.join(__dirname, "images", "products")), );
问题描述
尝试将MERN应用部署至Vercel,前端React网站从后端获取静态图片。部署后端后,其他路由可正常工作,但类似 https://deployed-web-api.vercel.app/images/products/product-1.png 的图片路由无法加载图片;本地环境中 http://localhost:4000/images/products/product-1.png 可正常加载。已尝试多种解决方案但未解决。
解决步骤
1. 调整Vercel路由优先级
Vercel路由按匹配顺序执行,当前第一个路由/(.*)会匹配所有请求(包括图片路径),导致图片请求被直接转发到根目录,无法触发express静态资源中间件。需将图片路由放在最前面:
{ "version": 2, "builds": [ { "src": "./index.js", "use": "@vercel/node" } ], "routes": [ { "src": "/images/(.*)", "dest": "/images/$1" }, { "src": "/(.*)", "dest": "/" } ] }
2. 确认静态资源目录被正确打包
检查项目根目录的.vercelignore文件,确保没有将images目录加入忽略规则,否则图片资源不会被上传到Vercel服务器。
3. 简化express静态资源挂载逻辑
调整index.js中的静态资源挂载代码,确保路径匹配更准确:
const path = require('path'); const __dirname = path.resolve(); // 直接挂载/images根路径,自动匹配子目录下的资源 app.use('/images', express.static(path.join(__dirname, 'images')));
4. 本地验证部署包
使用Vercel CLI执行vercel build命令本地构建,查看.vercel/output目录下是否包含images文件夹及对应图片文件,确认资源被正确打包。
内容的提问来源于stack exchange,提问作者MERN Stack Developer
相关产品推荐
相关产品推荐

