Utilizing Node.js as a web server allows it to solely focus on fulfilling your requests, whether it's serving pages or static assets like images, fonts, CSS, and JavaScript files.
For instance, when a user needs to log in, you can set up the index page with a "login" link that directs them to a /login route:
app.get('/', function(req, res){
res.render('index', { title: 'home' });
});
In the index.ejs file:
<!DOCTYPE html>
<head>
<title><%= title %></title>
</head>
<html>
<body>
<a class="btn" href="/login">LOGIN</a>
</body>
</html>
Upon requesting http://yourdoamin.com/
, Node will serve this index page. However, without any styling or scripting, it lacks interactivity. To address this, configure Node to also serve jQuery along with the index page:
app.use(express.static(__dirname + '/public'));
Create a public folder containing styles and scripts:
/public
/css
bootstrap.css
myStyles.css
/js
jQuery.js
bootstrap.js
myScripts.js
/images
/fonts
Include these styles and scripts in your index.ejs:
<!DOCTYPE html>
<head>
<title><%= title %></title>
<link rel="stylesheet" href="/css/bootstap.css">
<link rel="stylesheet" href="/css/myStyles.css">
</head>
<html>
<body>
<a class="btn" href="/login">LOGIN</a>
<!-- scripts -->
<script src="/js/jQuery.js"></script>
<script src="/js/myScripts.js"></script>
</body>
</html>
Now, by accessing http://yourdoamin.com/
, Node will also provide jQuery to the client-side due to its capability of serving static assets. (Alternatively, a CDN can be used for jQuery instead of a static file.)
With jQuery available on the client-side, actions like clicking "login" can be enhanced - preventing the default behavior and displaying a login form popup (utilizing tools like Bootstrap modals):
In myScripts.js file:
$('.btn').click(function(event) {
event.preventDefault();
var modalTemplate = $('#modalTemplate').html();
$('#modal').html(modalTemplate);
$('#modal').modal('show');
});
In index.ejs:
<!DOCTYPE html>
<head>
<title><%= title %></title>
<link rel="stylesheet" href="/css/bootstap.css">
<link rel="stylesheet" href="/css/myStyles.css">
</head>
<html>
<body>
<div id="#modal" class="modal fade"></div>
<a class="btn" href="/login">LOGIN</a>
<!-- scripts -->
<script src="/js/jQuery.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/myScripts.js"></script>
<!-- client-side templates -->
<script type="text/template" id="modalTemplate">
<div class="modal-dialog">
.
<!-- refer to Bootstrap documentation -->
.
</div>
</script>
</body>
</html>
This process embodies the concept of Progressive enhancement. Clicking "login" initially redirects to the login page, but users with modern browsers (JavaScript enabled) are presented with a modal login form instead.
While manual client-side development is effective, frameworks like Angular, Ember, as well as tools such as Backbone, React, etc., offer more structured solutions for extensive projects.