Heroku部署Node.js项目后无法加载静态资源求助
Hey there! Let's get your static assets (from public and node_modules) loading properly on Heroku—since it's your first time deploying here, I know this can feel a bit overwhelming, but we'll work through it step by step.
First, Let's Diagnose the Key Issues in Your Current Code
Looking at your app.js, the main problem is likely how you're resolving file paths. process.env.PWD and process.cwd() can behave unexpectedly on Heroku because of how the platform structures deployment directories. Instead, we'll use __dirname—this variable reliably points to the directory of your app.js file, which is your project root.
Also, the order of your middleware matters: static asset handlers should run before your route handlers, so requests check for static files first before hitting your routes.
Here's the Revised app.js Code
I've cleaned up redundant imports, fixed path resolution, and adjusted middleware order:
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var fs = require('fs'); var bodyParser = require('body-parser'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var app = express(); var http = require('http').Server(app); // Use __dirname for reliable root path resolution const rootDir = __dirname; // View engine setup app.set('views', path.join(rootDir, 'views')); app.set('view engine', 'ejs'); // Static asset middleware - placed BEFORE routes app.use(express.static(path.join(rootDir, 'public'))); // Serves files from /public at root URL app.use('/scripts', express.static(path.join(rootDir, 'node_modules'))); // Serves node_modules at /scripts app.use('/jsonfiles', express.static(path.join(rootDir, 'jsonfiles'))); // Serves jsonfiles at /jsonfiles // Other middleware app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // Routes app.use('/', indexRouter); app.use('/users', usersRouter); // Catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // Error handler app.use(function(err, req, res, next) { // Set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // Render the error page res.status(err.status || 500); res.render('error'); }); // Start server http.listen(process.env.PORT || 8000, function() { console.log('listening on *:' + (process.env.PORT || 8000)); }); module.exports = app;
Additional Critical Checks
Make Sure Your Static Folders Are Committed to Git
Heroku deploys from your git repository, so ifpublic,jsonfiles, or any required assets aren't committed, they won't exist on Heroku. Check your.gitignorefile—if it has lines likepublic/orjsonfiles/, remove them. Then run:git add public jsonfiles git commit -m "Add static asset folders" git push heroku mainCheck Heroku Logs for Specific Errors
To see exactly which assets are failing to load, run this command in your terminal:heroku logs --tailLook for lines like
404 Not Foundfor specific files—this will tell you if the path in your code doesn't match what's actually on Heroku.Avoid Exposing Entire
node_modules(Optional)
Serving the wholenode_modulesfolder isn't ideal for security and performance. Instead, consider only serving specific packages you need (e.g.,/scripts/jqueryinstead of/scriptspointing to all ofnode_modules). But if you need the whole folder, the code above will work.
Test It Out
After making these changes, push your updated code to Heroku and refresh your app. Your static assets should now load correctly!
内容的提问来源于stack exchange,提问作者user3401697

