Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!