0

I have an HTML project that I want to send to the user's browser via nodejs. Since each HTML file has a set of linked files like style.css, how do we do that? Do I have to use "app.use" in express.js? Because in this case I have to send the whole project files (even unvisited pages file) to the user !!!

  • Does this answer your question? [adding .css file to ejs](https://stackoverflow.com/questions/18629327/adding-css-file-to-ejs) – Alex Collette Jul 03 '21 at 03:42

1 Answers1

0

We do what is called a "public" folder. Inside this public folder, anyone can access these files. If your domain was example.com, and inside the public folder we have style.css, we can access sit by example.com/style.css. Any other files that are not in the public directory the user will not be able to access (unless you manually serve them in Express).

You do it in Express like this:

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

So put all the files you want to access in the HTML file in the public directory.

You can link a CSS file in your HTML file (in the head tags) like:

<link rel="stylesheet" type="text/css" href="/style.css" />

Here's what you directory can look like:

- index.js (your main server)
- / public
  - style.css
  - someOtherFile.js
  - etc...
- Your other files...
code
  • 5,690
  • 4
  • 17
  • 39