Bird
0
0

Why does this Express app fail to serve static files?

medium📝 Debug Q7 of 15
Node.js - HTTP Module
Why does this Express app fail to serve static files?
const express = require('express');
const app = express();
app.use('/static', express.static('public'));
app.listen(3000);

Accessing http://localhost:3000/image.png returns 404. What is the fix?
AChange URL to include /static prefix
BRename folder from public to static
CRemove app.listen call
DUse app.get instead of app.use
Step-by-Step Solution
Solution:
  1. Step 1: Understand the mount path for static files

    The static files are served under the '/static' path, so accessing root '/' won't find them.
  2. Step 2: Fix the URL to match mount path

    Accessing http://localhost:3000/static/image.png will serve the file correctly.
  3. Final Answer:

    Change URL to include /static prefix -> Option A
  4. Quick Check:

    URL must match static mount path [OK]
Quick Trick: Match URL path with static middleware mount path [OK]
Common Mistakes:
  • Ignoring mount path prefix
  • Renaming folders unnecessarily
  • Misusing app.get for static files

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes