Full-Stack Web Development with Vue.js and Node

(singke) #1
Building Authentication with passport.js Chapter 6

With these updated, let's build our application once more with the following command:


$ npm run build

Our application should work as expected.


Since our application is a Single Page Application (SPA), when we browse through the
nested routes and reload the page, we will get an error. For example, if we browse


the http://localhost:8081/contact page by clicking the link in the home page, it will


work. However, if we try to navigate to the http://localhost:8081/contact page


directly, we will get an error because this is an SPA, which means that the browser only
renders the static index.html file. When we try to access the /contact page, it will look


for the page called contact, which does not exist.


For this, we will need to add a middleware, which acts as a fallback and renders the
same index.html file when we try to reload the page directly or try to access the pages


with dynamic IDs.


There is a middleware provided by npm to serve our purpose. Let's go ahead and install the


following package:


$ npm install connect-history-api-fallback --save

After the installation, let's modify our server.js file to use the middleware:


...
const passport = require('passport');
const serveStatic = require('serve-static');
const history = require('connect-history-api-fallback');
const app = express();
const router = express.Router();

...

// Include controllers
fs.readdirSync("controllers").forEach(function (file) {
if(file.substr(-3) == ".js") {
const route = require("./controllers/" + file)
route.controller(app)
}
})
app.use(history());
app.use(serveStatic(__dirname + "/dist"));
...
Free download pdf