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
  • 183
  • 1
  • 1
  • 5
  • It will help you I guess https://stackoverflow.com/questions/25463423/res-sendfile-absolute-path – Always Sunny Oct 03 '17 at 00:30
  • FYI: with debugging you'll see that `app.get('/', function (req, res) {` doesn't get called when you request `http://localhost:3000/` – Jaromanda X Oct 03 '17 at 01:44
  • While it is possible to serve static files with node.js, it is always better to use nginx for it. – Jehy Oct 03 '17 at 07:33

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
  • 475
  • 5
  • 19