Express JS Tutorial
Introduction
- Is a framework that can be used with NodeJS
- You can build a web app and APIs
- It supports many features as a plugin which makes it easy
- 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
- Routing defines the endpoint for URL
- The endpoint is a complete URL, which accepts the client request and sends a response
- Every routing will be registered with HTTP methods GET, POST, PUT, DELETE, PATCH etc
- 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
- Syntax: app.METHOD(PATH, HANDLER)
- app: is an instance of express
- METHOD: is an HTTP request method, in lowercase
- PATH: is a path on the server
- 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
- express.static:\nIs a built-in middleware function in Express
- It helps in serving To serve images, CSS files, and JavaScript files
- Syntax: express.static(root, [options])
- root: It specifies the root directory from which to serve static assets
- options: It accepts params for set HTTP headers, redirect, extensions etc
- http://localhost:3000/images/profile.jpg
Express routing in-depth
- Route methods:\nA route method is derived from one of the HTTP methods
- 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
- app.all():\nIs a special method
- Is used to load middleware functions at a path for all HTTP request methods
- 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
- Route methods define the endpoints at which requests can be made
- 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
- Route parameters are named URL segments
- Are used to capture the values specified at their position in the URL
- 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
- 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
- You can provide multiple callback functions to handle a request
- 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
- res.download(): Prompt a file to be downloaded
- res.end(): End the response process
- res.json(): Send a JSON response
- res.jsonp(): Send a JSON response with JSONP support
- res.redirect(): Redirect a request.
- res.render(): Render a view template.
- res.send(): Send a response of various types.
- res.sendFile(): Send a file as an octet stream.
- 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
- The express.Router class helps to create modular, mountable route handlers
- 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)