Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Express JS Tutorial

Introduction
  1. Is a framework that can be used with NodeJS
  2. You can build a web app and APIs
  3. It supports many features as a plugin which makes it easy
  4. Is server-side framework
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
    res.send('Hello World!');
});
app.listen(port, () => {
    console.log('Server running at http://localhost:3000');
});
//Output
// Server running at http://localhost:3000
// Hello World!
Basic routing
  1. Routing defines the endpoint for URL
  2. The endpoint is a complete URL, which accepts the client request and sends a response
  3. Every routing will be registered with HTTP methods GET, POST, PUT, DELETE, PATCH etc
  4. Every route has a handler function which will be executed when the endpoint or route is matched
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
    res.send('Hello World!');
});
app.listen(port, () => {
    console.log(`Server running at http://localhost:3000`);
});
//Output
// Server running at http://localhost:3000
// Hello World!
Routing structure
  1. Syntax: app.METHOD(PATH, HANDLER)
  2. app: is an instance of express
  3. METHOD: is an HTTP request method, in lowercase
  4. PATH: is a path on the server
  5. HANDLER: is the function executed when the route is matched
const express = require('express');
const app = express();
app.get('/getMethod', function (req, res) {
    res.send('Get method');
});
app.post('/postMethod', function (req, res) {
    res.send('Post method');
});
app.put('/putMethod', function (req, res) {
    res.send('Put method');
});
app.delete('/deleteMethod', function (req, res) {
    res.send('Delete method');
})
// output
// Get method
// Post method
// Put method
// Delete method
Serving static files
  1. express.static:\nIs a built-in middleware function in Express
  2. It helps in serving To serve images, CSS files, and JavaScript files
  3. Syntax: express.static(root, [options])
  4. root: It specifies the root directory from which to serve static assets
  5. options: It accepts params for set HTTP headers, redirect, extensions etc
  6. http://localhost:3000/images/profile.jpg
Express routing in-depth
  1. Route methods:\nA route method is derived from one of the HTTP methods
  2. Is attached to an instance of the express class
app.get('/getMethod', function (req, res) {
    res.send('Get method');
});
app.post('/postMethod', function (req, res) {
    res.send('Post method');
});
// output
// Get method
// Post method
Special method
  1. app.all():\nIs a special method
  2. Is used to load middleware functions at a path for all HTTP request methods
  3. Example: Below handler is executed for requests to the route “/api” whether using GET, POST, PUT, DELETE, or any other
app.all('/api', function (req, res, next) {
    console.log('Log API method')
    next()
})
Route paths
  1. Route methods define the endpoints at which requests can be made
  2. Route paths can be strings, string patterns, or regular expressions
app.get('/getMethod', function (req, res) {
    res.send('Get method');
});
app.post('/postMethod', function (req, res) {
    res.send('Post method');
});
// output
// Get method
// Post method
Route parameters
  1. Route parameters are named URL segments
  2. Are used to capture the values specified at their position in the URL
  3. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys
  4. We can append a regular expression in parentheses (()) to match/validate/format the params
app.get('/user/:userId', function (req, res) {
    res.send(req.params)
})
//Example:
//Request URL: http://localhost:3000/users/123
//req.params: { "userId": "123" }
Route handlers
  1. You can provide multiple callback functions to handle a request
  2. Route handlers can be in the form of a function, an array of functions
//Example:
const validatePayload = (req, resp) =>{
    //validate
}
const validateLogin = (req, resp) =>{
    // check if valid user
}
app.get('/profile', validatePayload, validateLogin, function (req, res) {
    res.send('Profile info')
})
// output
// Profile info
Response methods
  1. res.download(): Prompt a file to be downloaded
  2. res.end(): End the response process
  3. res.json(): Send a JSON response
  4. res.jsonp(): Send a JSON response with JSONP support
  5. res.redirect(): Redirect a request.
  6. res.render(): Render a view template.
  7. res.send(): Send a response of various types.
  8. res.sendFile(): Send a file as an octet stream.
  9. res.sendStatus(): Set the response status code and send its string representation as the response body
app.route()
You can create chainable route handlers for a route path by using app.route()
//Example:
app.route('/user')
    .get(function (req, res) {
        res.send('Get method')
    })
    .post(function (req, res) {
        res.send('Post method')
    })
    .put(function (req, res) {
        res.send('Put method')
    }).delete(function (req, res) {
        res.send('Delete method')
    })
express.Router
  1. The express.Router class helps to create modular, mountable route handlers
  2. A Router instance is a complete middleware
//Example:
// Create a file userRotes.js and place the code
var express = require('express')
var router = express.Router()
// Get user details
router.get('/details/:userId', function (req, res) {
    res.send('User details')
})
router.get('/create', function (req, res) {
    res.send('Create user')
})
module.exports = router
// create a file index.js
const express = require('express');
const app = express();
var user = require('./user')
app.use('/user', user)