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

451
Visualizações
Node.js + Express: What do I have to serve the specific folder's path to express.static?

I wrote the following code:

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

app.use('/', express.static(__dirname ));

app.get('/', function (req, res) {
  res.sendFile('./dist/index.html');
});


app.listen(3000, function() {
  console.log("Listening on port 3000");
});

which doesn't work. When open the browser and go to "localhost:3000" I get the error:

path must be absolute or specify root to res.sendFile

Of course the once I fix the line that starts with "app.use..." to:

app.use('/', express.static(__dirname + "./dist"));

then everything works right.

Can you please explain why? What's wrong with giving "express.static" a path of a parent folder of the direct folder of the file sent?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Try changing the order. Instead of:

app.use('/', express.static(__dirname ));

app.get('/', function (req, res) {
  res.sendFile('./dist/index.html');
});

Try:

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, './dist/index.html'));
});

app.use('/', express.static(__dirname));
// OR:
app.use('/', express.static(path.join(__dirname, 'dist')));

Plus use path.join() to join paths. You need to require path first:

var path = require('path');

See this answer for more info on serving static files and why path.join is important:

  • How to serve an image using nodejs

Now, your problem was not about express.static but about res.sendFile. When you changed express.static path to a different one, then the file you previously wanted to send with res.sendFile was probably found by express.static and the handler with res.sendFile was not run at all. Before the change, the express.static wasn't finding the index.html file and was passing the request to the next handler - which had a bad res.sendFile invocation. That's why it appeared to solve the problem with the error, because the code causing the error was no longer called.

over 4 years ago · Santiago Trujillo 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