Express Apps

Express Apps

Server applications build with node framework

Let's make node.js super cool, easy (whatever you call it) using express.js framework

TL;DR

Node.js is a platform for building the server applications which are server-side event-driven and made using JavaScript. Express.js is a framework based on Node. We've been talking about node.js so far but the code becomes super messy as the complexity of application grows, so that we've got many frameworks which does some work behind and make it easy to build larger apps, one such is express.js.

Express.js

Rather than solving issue with the spaghetti code node would create, express comes with irreplaceable addon features;

Mainly express focus on robust routing that is 10x better than the filesystem based read/write routes in core node.

  • Generating applications quickly
  • Robust routing
  • High performance
  • HTTP helpers (redirection, caching, etc)
  • View system supporting 14+ template engines

Getting started

Pre-requisites: basics of JavaScript and Node.js

node -v   /*check if node is installed properly*/
npm install express   /*In root of the repo*/

Express Server App

So let's get back to action, here's what were going to do down below in code;

  • Require the express module from node modules

const express = require('express');

  • Instantiate the module to create a instance

const app = express();

  • Listen to the port and respond to the url's
app.listen(3000, () => {
   console.log("server listening to port 3000!")
});

app.get('/', (req, res) => {
   res.send('<h1>Welcome to My server</h1>');
})
node server.js    /*would start the server*/

Folder structure

express__server  
|     
|__views       
|     |_index.html
|     | 
|     |_blogs.html
|     |
|     |_404.html
|
|__server.js  
|

Complete server code

server.js

const express = require('express');

const app = express();

app.listen(3000, () => {
   console.log("server listening to port 3000")
});

app.get('/', (req, res) => {
  res.sendFile('./index.html', { root: __dirname });
})

app.get('/blogs', (req, res) => {
  res.sendFile('./blogs.html', { root: __dirname });
})

// REDIRECTS /blog to /blogs
app.get('/blog', (req, res) => {
  res.redirect('/blogs');
})

// 404 - other than any url's land up here
app.use((req, res) => {
  res.status(404).sendFile('./404.html', { root: __dirname });
})

Major Takeaway

Express a node framework replace the spaghetti code build with core node.js, with it's elegance in significantly lesser code.