You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Heroku部署Node.js项目后无法加载静态资源求助

Fixing Static Assets Loading on Heroku for Your Node.js App

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 if public, jsonfiles, or any required assets aren't committed, they won't exist on Heroku. Check your .gitignore file—if it has lines like public/ or jsonfiles/, remove them. Then run:

    git add public jsonfiles
    git commit -m "Add static asset folders"
    git push heroku main
    
  • Check Heroku Logs for Specific Errors
    To see exactly which assets are failing to load, run this command in your terminal:

    heroku logs --tail
    

    Look for lines like 404 Not Found for 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 whole node_modules folder isn't ideal for security and performance. Instead, consider only serving specific packages you need (e.g., /scripts/jquery instead of /scripts pointing to all of node_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:41:18