Vercel单仓部署:同域名下React客户端与Node服务端部署异常
部署同域名React+Node.js项目到Vercel时的静态文件路由问题
我正在Vercel上部署包含React客户端和Node.js服务端的项目,想把两者放在同域名下避免跨域。本地运行正常,客户端和API都通过localhost:4000提供服务,但部署后遇到路由问题:React构建后的静态文件无法从client/dist正确加载,要么提示dist缺失,要么访问静态文件返回404。
目录结构
my-project/ ├── client/ │ ├── src │ ├── other client side stuff... ├── server/ │ ├── index.js │ ├── other server side stuff... ├── package.json # Root package.json for the monorepo └── vercel.json # Vercel configuration for both client and server
根目录package.json
{ "name": "", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "npm install --prefix server && npm install --prefix client && npm run build --prefix client", "start": "npm run start --prefix server", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
server/index.js
const isProduction = process.env.NODE_ENV === "production"; const __dirname = path.resolve(); if(isProduction){ app.use(express.static(path.join(__dirname, "../client/dist"))); app.get("*", (req, res) => { return res.sendFile(path.join(__dirname, "../client/dist/index.html")); }); }
vercel.json
{ "version": 2, "builds": [ { "src": "server/index.js", "use": "@vercel/node" }, { "src": "client/package.json", "use": "@vercel/static-build", "config": { "distDir": "dist" // This throws 404 where as using "client/dist" throws 500: dist is missing } } ], "rewrites": [ { "source": "/api/(.*)", "destination": "/server/index.js" }, { "source": "/(.*)", "destination": "/client/dist/$1" // Serve static files from client/dist } ] }
说明:我知道可以把客户端和服务端部署在不同域名下,但希望保持同域名部署以避免CORS问题并简化流程。
内容的提问来源于stack exchange,提问作者Juhil Savani
相关产品推荐
相关产品推荐

