Home > Enterprise >  Why the styling is not working in my express app?
Why the styling is not working in my express app?

Time:03-01

The stylings are not working in this route: 'http://localhost:5000/exams/add-new'

But it is working with the other routes such as:

  • 'http://localhost:5000'
  • 'http://localhost:5000/exams'
  • 'http://localhost:5000/about'

I have my CSS file in the assets folder: assets/css/styles.css

Here is the server.js file:

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

app.set('view engine', 'ejs')

app.use('/css', express.static(path.resolve(__dirname, 'assets/css')))

app.use('/', require('./server/routes/router'))

app.listen(5000)

And the index.ejs file in the views folder:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="css/styles.css" />
    <title>Home Page</title>
  </head>
  <body>
    <!--Header-->
    <header>
      <div>
        <nav>
          <h1 >
            <a href="/">B<span>log</span></a>
          </h1>
          <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/exams">Exams</a></li>
            <li><a href="/about">About</a></li>
          </ul>
        </nav>
      </div>
    </header>
    <!--/Header-->
    <br />

    <!-- Main Section -->
    <main>
     <h1>Home Page</h1>
    </main>
    <!-- Main Section -->
  </body>
</html>

And here is the exams page:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="css/styles.css" />
    <title>Home Page</title>
  </head>
  <body>
    <!--Header-->
    <header>
      <div>
        <nav>
          <h1 >
            <a href="/">B<span>log</span></a>
          </h1>
          <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/exams">Exams</a></li>
            <li><a href="/">About</a></li>
          </ul>
        </nav>
      </div>
    </header>
    <!--/Header-->
    <br />

    <!-- Main Section -->
    <main>
      <!-- Add New Question Button -->
      <div >
        <a href="/exams/add-new-questions">
          <span>Add new questions</span>
        </a>
      </div>
      <!-- Add New Question Button -->
    </main>
    <!-- Main Section -->
  </body>
</html>

Why is this happening and what is the solution?

CodePudding user response:

in your output HTML, make sure the CSS is loaded from path:

/assets/css/styles.css

instead of assets/css/styles.css

This will bring consistency despite the route of your current URL

CodePudding user response:

in Html Add exact path of css :

assets/css/styles.css
  • Related