Search code examples
cssnode.jsexpressmiddleware

Apply CSS styles with express middleware


how are you? I'm trying to use middleware in express js, something like this.

app.get ('/user/:school/:dual', function (req, res, next) {
  ......
  ...
  ......
});

So far no problem.

When I enter a route for example: For example localhost:4000/UCLA/2019

The styles that have been defined are not displayed.

I am using static files in express js in the public folder

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

//app.use(express.static(__dirname)); // Current directory is root
app.use (express.static (path.join (__ dirname, 'public'))); // "public" off of current is root

app.listen (4000);
console.log ('Listening on port 4000');

The Public folder is defined by these folders

* Images
  -school
  -Light
* Vendor
  * Bootstrap
    * dist
       * css
         -file1.css
         -file2.css
       * fonts
       * js

I tried to remove all the folders to be able to access the static files faster, but I try to access the localhost:4000/UCLA/2019 and css styles do not appear.


Solution

  • I've been through this before. Once of the recommendations for you is to route the :4000 requests using apache reverse proxy, sometimes using the port is a real issue with static files.

    If this is not a solution for you, please use:

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

    instead of

    app.use (express.static (path.join (__ dirname, 'public')));
    

    and try placing a static file on the public folder, let me see how this is going