如何让Express从上级目录提供静态文件?含项目场景与已用解法
Hey there, let's work through this for your specific directory setup!
Your server.js lives in src/server/, but your static assets are tucked away in src/client/public—so we need to build a reliable path from the server file up to that public folder. Here's how to do it properly:
Step 1: Require the path module
First, make sure you've imported Node's built-in path module at the top of your server.js—it handles path joining safely across different operating systems (no more cross-platform path bugs!):
const express = require('express'); const path = require('path'); // Don't skip this! const app = express();
Step 2: Configure express.static with the correct path
Now use path.join() to combine __dirname (which points directly to the folder holding your server.js—that's src/server/) with the relative path up to your public assets:
// This resolves cleanly to your src/client/public folder app.use(express.static(path.join(__dirname, '../client/public')));
Why this works
__dirnamegives you an absolute path to the directory ofserver.js, so you never have to worry about broken paths if you start your server from a different folder (relative paths can fail here!).../moves up one level fromsrc/server/tosrc/, thenclient/publicdirects you straight to your static files.
You mentioned you already solved it with path.join(__dirname, '/../client/public')—that works perfectly too! The leading slash in '/../' doesn't cause issues, since path.join automatically normalizes the path to be clean and valid.
内容的提问来源于stack exchange,提问作者dvg

