Adityo Pratomo
Adityo Pratomo

Reputation: 263

Different Path for Serving Static HTML files in Express

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.

Upvotes: 1

Views: 522

Answers (1)

darth-coder
darth-coder

Reputation: 762

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.

Upvotes: 1

Related Questions