Home > Software design >  Css file not loading using Express JS backend on react project
Css file not loading using Express JS backend on react project

Time:06-09

Before asking this question I researched around SO and found a few things but one of them worked in my scenario. I'm trying to load my React website from an Express backend server.

My folder structure is as follows:

client
  build
    css
      styles.css
    index.html
server
  server.js

I'm just trialing and experimenting with express right now mainly to learn a bit more about it and my server.js file looks like this

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

app.get("/api", (req, res) => {
    res.json({"users": ["userOne", "userTwo"]})
})

app.use(express.static(path.join(__dirname, "..", "client", "build")));
app.use(express.static("../client/public"));

app.listen(5000, () => console.log("server started on port 5000"))

My index.html head

<meta charset="utf-8" />
  <link rel="icon" href="./images/logo.png" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#000000" />
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link type="css" rel="stylesheet" href="/css/styles.css" />
  <meta name="description" content="Welcome to Sintra Welcome Centre" />
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script type="text/javascript"
    src="https://cdn.rawgit.com/prashantchaudhary/ddslick/master/jquery.ddslick.min.js"></script>
  <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

When I run the server on port 5000 I can see the HTML being loaded up fine but I can't see any reference to the styles.css file anywhere, checking on the network tab it seems it isn't being loaded at all.

Can anyone spot my error? Thank you

CodePudding user response:

The markup validator would have picked up this error if you had used it.

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

The only MIME type browsers recognise for CSS is text/css.

You've told it to expect css (which isn't a valid MIME type anyway) so the browser believes it can't use the stylesheet because it isn't in a known format.

Consequently it doesn't try to load it.

Omit the type attribute.

  • Related