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

148
Visualizações
Express Only loads main page

I'm trying to learn express. I'm using FS to load my HTML Page. The only thing I could find on this with a google search was using ASP.NET instead of Express.

Server.js:

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

var app = express();

app.use(require('body-parser').urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname+'/')))

app.get('/', function(a,b,c){
  fs.readFileSync('index.html');
});

app.post('/testaction', function(a,b){
    console.log(a.body.log);
    fs.readFileSync('Logged.html');
});

app.listen(3000);

index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Test Page</title>
  </head>
  <body>
    <form method="post" action="http://localhost:3000/testaction">
      <h1>Log This:</h1>
      <input type="text" name="log"/>
      <input type="submit", value="Press Me!"/>
    </form>
  </body>
</html>
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In order to serve files you don't have to use fs. Example:

app.get('/', function(req, res, next) {
  res.render('index');
});

If you need to redirect, you can use:

res.redirect('/staticFile.html');
about 4 years ago · Santiago Trujillo Relatório

0

Remove these lines:

app.get('/', function(a,b,c){
  fs.readFileSync('index.html');
});

This line is middleware and it applies to all routes on every request:

app.use(express.static(path.join(__dirname+'/')))

It's purpose is to serve static files from whatever path you provide. In this case you're serving from the root directory so you can navigate to all your code files like http://localhost:3000/package.json for example.

It applies to all HTTP methods, get post put etc...

When you write app.get('/' you override that middleware with a new route and try serving only one file. Just drop that code and you'll server everything statically from the directory you specified above.

If you don't want to serve your code files, put your static files in a different folder such as "site" and set your static path to that folder, for example:

app.use('/', express.static(__dirname + '/site'));
about 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