Configure your server to work with html5 history using node.js

The HTML5 History API gives developers the ability to do many things which was not available in old version of html.One of the most important feature is modify a website’s URL without a full page refresh.This is particularly useful for loading portions of a page with JavaScript,
such that the content is significantly different and warrants a new URL.

The most of JavaScript Frameworks like backbone.js,angularjs providing the client side routing which let you change the
browser URL without refresh page but when we use server side technology like node.js we may define all the routes again on server side
is it work when user press F5 or ctrl+f5 and user can get something like `Cannot GET /home`. So in this post i am going to show you how you can configure your node.js server so it can work with
client side html5 History API.

Create a simple server using express.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});

var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

Now add this route handler which will handle all the other requests which are not defined and make sure you have add this code after
define all routes:-

app.all("/*", function(req, res, next) {
res.render('index', { title: 'Express' });
});

Add a Comment

Your email address will not be published. Required fields are marked *