How to use static? (express)

Hello, I’ve just recently started using express.js so sorry if this is a basic question or if I have any misconceptions/incorrect terms –

In my main server.js file, I’ve included app.use(express.static('static')) and then created a folder called ‘static’ that contains the file index.html

However, when I try to access index.html it gives me the error

Error: ENOENT: no such file or directory, stat ‘/app/index.html’

When I move index.html out of the folder ‘static’, the page loads as normal. But the minute I put it into the static folder it stops working? :sweat_smile:

that’s seems like there’s other code that’s looking for it out in /app. is there a stack trace that comes with that error? it might help you locate that other code.

This might work
app.get("/", function (request, response) { response.sendFile(__dirname + "/static"); });
but I have mine set as app.use(express.static('public')) so it might be different for yours.

they said static was a folder. what will response.sendFile(__dirname + "/static"); do in that case?

I was thinking It might load or show the server that the file exists

In the most minimal way I can think of, the following works fine:

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

app.use(express.static("static"));

app.listen(process.env.PORT, () => {
  console.log(` Server's running`);
});

With a static/index.html file that just contains <h1>yay</h1> you will see a nice big bold yay front and center left-aligned in your preview. So start with that, and then build that out with app.get and app.post instructions after the app.use instruction. Express uses the “if more than one thing matches the requested URL, the first handler that got declared in the code wins”, so this won’t work for example:

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

app.get(`/`, (req, res) => {
  res.send("lol");
});

app.use(express.static("static"));

app.listen(process.env.PORT, () => {
  console.log(` Server's running`);
});

It will instead show “lol”, because the explicit get handler for / was declared before the app.use.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.