1

I am beginner in express, js and node.js

I have followed lot of tutorials about express, and i dont understand why the index.html file dont call the corresponding CSS file:

my server.js file:

const path = require('path')
const express = require('express');

var app = express();

app.use(express.static('public'));

app.get('/0', (req, res) => {
    res.sendFile('index.html', {root : __dirname });
})

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
 })

my index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="/public/css/style.css">
    <title>Pt02 Ch02 Exercise 200</title>
</head>
<body>

  <div class="container">
    <div class="heading">Aidez-moi à arrêter de crier !</div>
    <div class="heading">Je veux rester en majuscules !</div>
  </div>
  
</body>

my CSS file:

@import url('https://fonts.googleapis.com/css?family=Montserrat:100,900i');
html, body {
  font-family: 'Montserrat', sans-serif;
  height: 100%;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: blue;
}

.container {
  height: 100%;
  align-items: center;
}

.heading {
  width: 100%;
  padding: 1.5rem 2.5rem;
  margin-bottom: 1.5rem;
  background: #15DEA5;
  color: #FFF;
  font-size: 2rem;
  text-transform: uppercase;
}

and the different folders of the project:

enter image description here

when i type localhost:8081/0, the result is not the right result, the CSS is not active.

What am i doing wrong? thanks for help

1
  • That public \ css folder name looks odd unless is a VSCode name thing, but try <link rel="stylesheet" href="/css/style.css"> instead Commented Oct 20, 2020 at 14:08

2 Answers 2

3

express.static bind public folder to site root (/) so after that you need to include static files without public in path:

    <link rel="stylesheet" href="/css/style.css">
Sign up to request clarification or add additional context in comments.

Comments

0

Are you sure your CSS is under public/css ? and not public\css I'm not an expert, but I think that must be the issue. The folder of the project is named public\css, while your stylesheet rel is connected to public/css.

EDIT The user above told the right answer I guess, statics folders shall not be listed in the html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.