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?
I know that Express apps default to port 3000.
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.
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); });
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" } ); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With