Home > Back-end >  Static serving on express js not working when also using custom middleware
Static serving on express js not working when also using custom middleware

Time:11-21

I am trying to write a middleware for my express js website so that I can use subdomains. I also want to use static image, css, and js serving. My HTML pages load just fine but whenever I try to call a .js file, I get a long page load time and the js doesn't load.

Any help is appreciated, thanks! :)

app.use("/assets", express.static(path.join(__dirname, "assets")));

app.get("*", (req, res, next) => {

let host = req.get("host").split(".");
console.log(req.originalUrl);

let url = req.originalUrl.split("/");
url.shift();
console.log(url);

if (host.length > 2) {
    res.send("myWebsite.com");
} else {
    const pages = Page.getPages();
    pages.forEach(page => {
        if ((url[0] == "" ? "home" : url[0] ?? "home").toLowerCase() == page.name) {
            if (url.length == 1 || (url.length == 2 && url[1] == "")) {
                page.publish(res);
            }
        }
    });
}

});

CodePudding user response:

So, in Pages.html, you have this:

<script type="text/javascript" src="/assets/js/Pages.js"></script>

That looks like it would generally be compatible with your express.static() statement (shown below) to load Pages.js from your assets/js folder:

app.use("/assets", express.static(path.join(__dirname, "assets")));

But, then that Pages.js script immediately starts out with this:

import Page from '../../Page.js';

That will not work when requested by the browser. Remember paths in import statements from Javascript running in the browser are relative to the current URL of the web page. The browser will attempt to combine that relative URL with the URL of the web page and then make a request to your server for that newly constructed URL.

In this case, you'll end up with something like a request for http://somehost/../../Page.js. But, you don't have any route in your server that will handle that. By default express.static() skips any routes that contain ../ because that can be a nasty security issues (allowing attackers to fetch things around your server file system). So, you'll probably end up with a 404 error when trying to fetch that file.

ALL files you want the browser to be able to load, including imports embedded within other JS files must be in your public assets folder (or some other folder you've explicitly enabled public access to with something like express.static()).

FYI, if you look in the browser console, you probably see error messages that would have indicated to you where to look for the error.

CodePudding user response:

__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file. You have to make sure that the final bundle (your asset folder) is present in that directory. Try to hard code the assets absolute path, if it works then use the below snippet instead:-

app.use("/assets", "express.static(process.cwd()   '/assets'));
  • Related