Serving static HTML, JavaScript, CSS files with Express.

How to serve a content according to a requested URL is demonstrated in most for beginners' Express and NodeJs tutorials . But sending just a string is not enough for considerable project. Created  HTML, JavaScript and CSS files should be served when get a user request.

See this HTML page
This was taken from a previous post of How to upload files with express.

<!DOCTYPE html>
<html>
<head>
<title>File Uploading Form</title>      
</head>
<body>
<h3>File Upload:</h3>
Select a file : <br />
<form id = "uploadForm" enctype =  "multipart/form-data" action="/upload" method = "post" >
<input type="file" name="upload_file" />
<input type="submit" value="Upload" name="submit">/form>
    
    <script src="/jquery-1.11.3.js"></script>
    <script src="/upload.js"></script>    
</body>
</html>


When user entered the url of our site ( "localhost:3000" since we are testing in our machine :) ) this html file should be served instead of a useless string (like welcome in tutorials).

Here is how it can be done

app.get('/',function(req,res){
      res.sendFile(__dirname + "/upload.html");
});


Here __dirname gives the name of the directory that the currently executing script resides in.

In the serving HTML file you can see there are references to a JQuery file and another javascript file (upload.js) to serve those static file we should let our server know where the static file are located.

It can be done like this

app.use(express.static('scripts'));

This statement let server know that all static files are in "script" directory. Path should be mentioned relative to script folder when adding references to files in HTML

Here is the complete server code for what we have done so far

var express =   require("express");
var app         =   express();
app.use(express.static('scripts'));

app.get('/',function(req,res){
      res.sendFile(__dirname + "/upload.html");
});
app.listen(3000,function(){
    console.log("listening on port 3000");
});

Please add a comment if this was useful or you have something to add.

No comments:

Post a Comment