Search code examples
htmlnode.jsexpresshttpstatic-files

Cannot access static files from URL in express application


I have built a basic express app as below -

index.js

const express = require("express");
const app = express();

app.use(express.static(__dirname + "public"));

app.get("/", (req, res) => {
  res.json({ message: "Hello World!" });
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

I want to serve static files directly from the browser URL, and according to this express doc page it is indeed possible.

Accordingly, I have created a folder called public in the root folder and have kept two files in it - one demo.html, and one image.jpg. My folder structure -

express-app
  |- index.js
  |- public
    |- image.jpg
    |- demo.html

However, when I try to access http://localhost:3000/demo.html or http://localhost:3000/image.jpg, I get a Cannot GET error.

image.jpg demo.html

Can anybody please tell me why it isn't working?


Solution

  • app.use(express.static(__dirname + "public"));
    

    __dirname does not include a trailing slash.

    __dirname + "public" will give you something like: /home/me/express-apppublic — a directory that doesn't exist.

    The documentation you link to shows the use of path.join to include the correct directory separator for your operating system.

    const path = require('path')
    app.use('/static', express.static(path.join(__dirname, 'public')))
    

    Don't omit that part!