Thursday, 21 February 2019

Express: app.all(path, callback [, callback ...]): Match to all http verbs


‘app.all’ is used to match all http verbs.

Below table summarizes the arguments of app.all method.

Argument
Description
Default Value
path
The path for which the middleware function is invoked. Path can be represented in string, regular expression, path pattern.

Ex: /abcd, /abc?d', /\/abc|\/xyz/ are valid paths.
/
callback
A callback function can be a middle ware function, series of middleware functions, array of middleware funcitons.


index.js
var express = require('express')

var app = express()

app.all('/*', (req, res) => {
 res.send('hello world')
})

app.listen(3000, () => {console.log("Application started in port 3000")});

Run the application on server. Whatever the requests PUT, GET, POST etc., and whatever the url patterns you use, you always get ‘hello world’ message.

You can provide multiple callback functions to all method.


index.js
var express = require('express')

var app = express()

loggingCallback = (req, res, next) =>{
 console.log("Logging user information")
 next()
}

authorizationCallback = (req, res) => {
 console.log("User credentials are validated")
 res.send("hello world")
}

app.all('/*', loggingCallback, authorizationCallback)

app.listen(3000, () => {console.log("Application started in port 3000")});

Run index.js and hit http://localhost:3000/*, * can by any string.

You can see below messages in console.
Logging user information
User credentials are validated

At the same time, you can see the message ‘hello world’ in browser.

The callbacks to the all method may not be required to act as final endpoints. They can call next method to call the next middleware.


index.js
var express = require('express')

var app = express()

loggingCallback = (req, res, next) =>{
 console.log("Logging user information")
 next()
}

authorizationCallback = (req, res, next) => {
 console.log("User credentials are validated")
 next()
}

app.all('/*', loggingCallback, authorizationCallback)

app.get('/hello', (req, res) => {
 res.send("Hello World")
})

app.get('/*', (req, res) => {
 res.send("Get request called")
})

app.listen(3000, () => {console.log("Application started in port 3000")});

Run index.js


And hit the url ‘http://localhost:3000/hello’, you can see ‘Hello World’  message in browser.

Hit http://localhost:3000/prefix prefix can by any string other than ‘hello’, you can see below message


Previous                                                 Next                                                 Home

No comments:

Post a Comment