Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplest way to have Express serve a default page?

Tags:

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.configure(function(){   app.use(express.bodyParser()); });  app.use(express.logger());  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?

like image 935
StevenV Avatar asked Jan 14 '14 16:01

StevenV


People also ask

What is the default express localhost port number?

I know that Express apps default to port 3000.

How do you create a simple express js application?

Step 1: Write this command in your terminal, to create a nodejs application, because our express server will work inside the node application. This will ask you for few configurations about your project you can fill them accordingly, also you can change it later from the package. json file.


2 Answers

I looked briefly for the best practices for serving a public folder and specifying the default page to serve. After reviewing the 'Express middleware' documentation, my solution looks like the following,

var express = require('express'); var app = express();  var options = {   index: "coming-soon.html" };  app.use('/', express.static('app', options));  var server = app.listen(8081, function () {   var host = server.address().address;   var port = server.address().port;    console.log('my app is listening at http://%s:%s', host, port); }); 
like image 175
Ryan Ruppert Avatar answered Oct 09 '22 13:10

Ryan Ruppert


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" } ); }); 
like image 42
Alex Curtis Avatar answered Oct 09 '22 13:10

Alex Curtis