Express Cheat Sheet

1/1/1970

Express Cheat Sheet

Setup Express

1. Initialize NodeJS Project

npm init # Interactive project setup.
npm init -y # Quick setup with defaults.

2. Install express

npm install express --save # `--save` is optional now

3. Create Index.js (entry point)

project
├── index.js
└── package.json

Build A Basic HTTP Server

1. Importing the Express framework

const express = require('express') // CommanJS
//or
import express from 'express' // ES Module

2. Creating an Express application instance - express()

const app = express()

3. Handling GET requests to the root URL ('/') - express().get()

app.get('/', (req, res) => { 
  res.send('Hello!') // Send "Hello!" as the response
})

4. Starting the server and listening on the specified port - express().listen()

app.listen(3000, () => {
  console.log(`app listening on port 3000`) // Logging a message when the server starts
})

Listen on dynamic Port

const port = 3000
app.listen(port, () => {
  console.log(`app listening at http://localhost:${port}`)
})

Set Custom Status Code for a Route

app.get('/contacts', (req, res) => {
  res.status(500); // Set status code to 500 (Internal Server Error)
  res.send('List of Contacts'); // Send response body
})

or

app.get('/contacts', (req, res) => {
  res.status(500).send('List of Contacts'); // More Concise way
})

Sending JSON as Response

app.get('/about', (req, res) => {
  res.json({"gaurav" : 169})
})

Sending HTML as Response

const path = require ('path')
// Route Handler
app.get('/about', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html' ))
})

Serving Static Files with Express Middleware

const path = require('path');
// Middleware `express.static()`
app.use(express.static(path.join(__dirname, "public")));

Create your own Middleware

// Middleware Function
const logRequest = (req, res, next) => {
	console.log(`Request URL: ${req.url}`);
	next(); 
};
// Use Middleware
app.use(logRequest)

Parameters in Routes/Endpoints

// name parameter
app.get('/hello/:name', (req, res) => {
	res.send('Hello World! ' + req.params.name)
})

express.Router().get() vs **`express().get()

express().get()

app.get('/hello', (req, res) => {
  res.send('Hello from App!');
});

express.Router().get()

const router = express.Router(); 
router.get('/hello', (req, res) => {
	res.send('Hello from Router!');
});
 
app.use('/app', router); // Mounting router at '/api'

Express Production App Structure

project
├── index.js # Main Entry Point of Express App
├── routes
      └── route.js
├── static # Static Files
|       └── Script.js
|       └── Style.css
|       
└── templates # HTML Templates
        └── index.html

Creating an Express blog app

Create index.js

project
	└──  index.js
// Index.js
const express = require('express')
const path = require('path')
const app = express()
const port = 3000
 
// Use Static File
app.use(express.static(path.join(__dirname, "static"))) 
 
// Use Route '/'
app.use('/', require(path.join(__dirname, `routes/blogRoute.js` )))
 
// Listen
app.listen(port, () => {
  console.log(`Blog app listening at http://localhost:${port}`)
})

Create index.html, blogHome.html & blogPage.html

project
	└──  templates
		└── index.html
		└── blogHome.html
		└── blogPage.html
<head>
	...
</head>
<body>
	...
</body>

Create blogData.js

project
	└──  data
		└──  blogData.js
// blogData.js
{
	blogs:[
		{
			title: "get start Python",
			content: "This is content",
			slug: "learn-python-beginner"
		},
		...
	]
}
 
// export blog data
module.exports blogs;

Create blogRoute.js

project
	└──  routes
		└──  blogRoute.js
const express = require('express')
const router = express.Router()  // create `Router` instance
const path = require('path') // inport built in `path` module
const blogs = require('../data/blogs') // // import blogData.js file

Route for Application Homepage index.html

// define '/' route on the `router` object
router.get('/', (req, res)=>{
	res.sendFile(path.join(__dirname, 'templates/index.html' ))
})

Route for Blog's Home page blogHome.html

// define '/blog' route on the `router` object
router.get('/blog', (req, res)=>{
	// Print each blog title
	blogs.forEach(elem =>{
		console.log(elem.title) 
	}); 
	// send `blogHome.html`
	 res.sendFile(path.join(__dirname, `templates/blogHome.html` )) 
})

Route for Each Blog Post blogPage.html

// Individual post routing through Parameter
router.get('/blogpost/:slug', (req, res)=>{
	// JS function to Filter the blogs array to find the blog with the matching slug
	myBlog = blogs.filter((elem)=>{
		return elem.slug == req.params.slug
	})
	 res.sendFile(path.join(__dirname, `../templates/blogPage.html` ))
});
// Export router
module.exports = router ⭐

Template Engines for Express


Handlebars

Handlebars.js -> templating engine for Node.js that can be used with Express to render web pages from server-side data to the client side.

Handlebars expressions are the basic unit of a Handlebars template, and are enclosed by double curly braces, {{}}

template: <p>{{firstname}} {{lastname}}</p>

Express-HBS

HBS (Express-HBS): A specialized package for using Handlebars within the Express framework, making integration with Express easier and more streamlined.


Express-Handlebars

Express-Handlebars** -> A specialized wrapper for using Handlebars with Express.js, offering better integration and configuration options.

Install express-handlebar: ⭐

npm install express-handlebars

Directory Structure:

Project
├── app.js   # or server.js
└── views
    ├── home.handlebars
    ├── blogHome.handlebars
    ├── blogPage.handlebars
    └── layouts
        └── main.handlebars

HTML to Handlebar

Setup handlebar

Modify app.js

// Import express-handlebars
import { engine } from 'express-handlebars'; // 
// Registers Handlebars as the template engine
app.engine('handlebars', engine());
// Registers Handlebars as the template engine for Express.
app.engine('handlebars', engine());
// Sets Handlebars as the default view engine for rendering templates.
app.set('view engine', 'handlebars'); 
// Specify the directory where the Handlebars views/templates are located.
app.set('views', './views');

Update get('/')

// Render the 'home' template from the views directory at  `/` route
app.get('/', (req, res) => {
    res.render('home');
});

Update get('/blog')

// handle bar syntax to render `blogHome.handlebars`
router.get('/blog', (req, res)=>{
	res.render('blogHome', {
	blogs: blogs
	});
})

Update get('/blogpost/:slug')

// handle bar syntax to render `blogPage.handlebars`
router.get('/blogpost/:slug', (req, res)=>{
	myBlog = blogs.filter((elem)=>{
		return elem.slug == req.params.slug
	})
	res.render('blogPage', {
		title: myBlog[0].title,
		content: myBlog[0].content})
});

Create main.handlebars:

...
<body>
	</nav>
		<a href="/"> Home </a>
		<a href="/blog"> Blog </a>
	</nav>
	{{{body}}}
</body>
...

home.handlebars

<h1>Welcome to Home </h1>

Create blogHome.handlebars

{{#each blogs}}
	<div class="blog">
		<a href="/blogpost/{{this.slug}}"></a>
		<h2> {{this.title}}</h2>
	</div>
	{{/each}}

Create blogPage.handlebars (Page for Each Posts)

<h2>{{title}}</h2>
<p>
	{{content}}
</p>

Note:


✅ Done