Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
Static serving on express js not working when also using custom middleware

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);
            }
        }
    });
}

});

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

__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'));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda