StevenV StevenV - 1 year ago 80
Node.js Question

simplest way to have Express serve a default page?

I'm using this to have Node.js/Express setup as a rudimentary web server - it just serves a set of static pages without any other processing. I'd like it to always serve /default.html when a browser fetches the site without any filename.

var express = require("express");
var app = express();
var port = process.env.PORT || 5000;



app.use(express.static(__dirname ));

app.listen(port, function() {
console.log("Listening on " + port);

I've tried using res.sendfile and res.redirect, but without much success; I'm obviously missing something as I end up with a 'has no method' error.

What would you say is the simplest way of achieving my goal?

Answer Source

You could do something like this. Assuming its an html file that is relative to the .js file:

app.get('/', function(req, res){
    res.sendfile('default.html', { root: __dirname + "/relative_path_of_file" } );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download