ExpressJS Routes
Routing
A route can be defined as,
app.METHOD(PATH, HANDLER)
- The app is an instance of express.
- METHOD is an HTTP request method(get, post,etc) in lowercase.
- PATH is a path on the server.
- HANDLER A handler function is called when the app receives a request to the given route and HTTP method. This is called “listening of requests”. Whenever, the request matches the provided route(s) and method(s), the specified callback function is called.
For example,
The routing methods can have multiple callback functions as arguments. But it is important to specify next as an argument to the callback function and then call next() within the body of the function to pass control to the next callback.
For example,
app.get('/', function (req, res) { res.send('Welcome to ExpressJS') }) //OR app.post('/', function (req, res) { res.send('Recieved a POST request') })
The routing methods can have multiple callback functions as arguments. But it is important to specify next as an argument to the callback function and then call next() within the body of the function to pass control to the next callback.
For example,
app.all('/someLocation', function (req, res, next) { console.log('Accessing the someLocation ...') next() // pass control to the next handler })
app.all() method
app.all('/someLocation', function (req, res, next) { console.log('Accessing the someLocaton ...') next() // pass control to the next handler })
Define Route paths
The route path appended with a request method are is used to define endpoints for which the request can be received. The route path can be string, string patterns or regular expression.
+, ?, * , (, ) can be used to produce regular expressions. However, - and . are interpreted literally in paths. The $ character can be used by simply enclosing it within ([ and ]). For example “/item/$price” can be used as “/item/([$])price”.
app.get('/ab+cd', function (req, res) { res.send('ab+cd') })