Reputation: 1092
I develop a web application using Node.js for the Back End and HTML/CSS/JS as Front End. I am attempting to build a single page app using Express framework.
I want to build a single page application using just Node.js or JavaScript, I know that for the response we could call something like res.render('contact')
, but this is not working in my case because I wan't to change dynamically my page, I don't want any additional frameworks like React, Angular, ...
On my index.html page, there is a menu that each of its elements contain a hyperLink. For example when clicking on contact hyperLink in index page, I want to display on the same page dynamically the content of contact page with forms...ect without loading the page :
<li> <a href="/contact">Contact</a></li>
My server.js file that defines the routes, by default I am directed to index page :
//to define the routes
var express = require('express'), app = express();
//to call multiple template engines easly, like html page...ect
var engines = require('consolidate');
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/public');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index');
});
app.get('/contact', function(req, res){
res.render('views/contact');
});
var server = app.listen(8080, function(){
console.log('Listening on port ' + server.address().port);
});
I know that SPA live on a single HTML document, but how I can do this with Express Framework without loading the pages? I am a bit lost.
Upvotes: 1
Views: 16017
Reputation: 5303
Your question is very broad, but I'll try to explain a few things that may help.
The job of Express is to handle HTTP requests and return responses. Some of those responses will be HTML files, perhaps with JavaScript and CSS.
To create an SPA, you will need to, at minimum, serve up a bundle of HTML and JavaScript to the client's browser as a starting point, usually an index.html
page.
This page, through JavaScript and HTML, can listen for events, including user actions and inputs, and make calls back to other endpoints on your Express server than can return data, snippets of HTML, or whatever you need to allow you to alter the single page that you have served to the user. But the changes must be executed by JavaScript that exists on the initial page, or scripts that are added by that initial JavaScript and executed.
You could for example use jQuery or fetch
to make calls back to your server, or even the basic web APIs in the browser. There are other tools available as well.
Upvotes: 5