1

Just a quick question. Say I have 2 different static HTML files that I want to serve in Express, index.html and contact.html. I've been fiddling around and I currently use this barebone Express code to serve them:

const express = require('express');
const path = require('path');

const app = express();

app.use(express.static('public'))

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

app.get('/contact', function (req, res) {
  res.sendFile(__dirname + '/public/contact.html');
});

app.listen(3000, function () {
  console.log('runnning on port 3000')
});

Question is, I tried to serve contact.html using

app.get('/contact', function (req, res) {
  res.sendFile(__dirname + '/contact.html');
});

but it always resort to the root directory instead of the public directory. OTOH, I can server index.html just fine without having to explicitly adding /public in the response.

Can anybody point me what's the cause for that?

Thanks.

Adityo Pratomo
  • 253
  • 1
  • 2
  • 7

1 Answers1

1

For the given file structure:

yourapp
 |-- contact.html
 |-- index.html
 `-- server.js

The following code would work just fine:

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

app.get('/contact', function (req, res) {
  res.sendFile(__dirname + '/contact.html');
});

Assuming both index.html and contact.html have read access.

Remember, sendFile requires an absolute path and __dirname refers to your app directory. Make sure you give references according to your file location.

darth-coder
  • 670
  • 8
  • 20