Serve static assets express

here is my code its not working:

var express = require('express');
var app = express();

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

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

app.get("/", (req,res) => {
  let absolutePath = __dirname + '/views/index.html'
  console.log('dirname: ',__dirname)	

 module.exports = app;

link to my repl:

my code is returning a 404 its not found

This is serving style.css at /style.css, not /public/style.css as linked in index.html.

ive done the following:

app.use(express.static(__dirname + '/public/style.css'));

its not working for me:

when i right click on the file manager in repl and click copy link it gives me the link as:

Your original code wasn’t wrong, it just didn’t align with the style sheet link in index.html. You have two choices: change the style sheet link or change your route to the static files. According to the docs, you can use

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

and serve style.css from /style.css or you can use

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

to serve the files in the directory public relative to the project’s working directory from the URL /public relative to the root URL (in other words, /public/style.css as both file location and URL). express.static() just says look in this directory for the static files; the directory/file name has no bearing on the URL that you may choose to assign to the static files.

Or you could change the style sheet link to style.css instead of /public/style.css, which is what I did while debugging.

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