-
determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
-
Each route can have one or more handler functions, which are executed when the route is matched.
- Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
Where:
app
is an instance ofexpress
.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.
simple helloworld app (index.js or whatever you want to call it
//require the Express module and call express //Following declares URI path / will cause the message Hello World to be sent
//application will listen for requests on port number 300 |
another example (index.js) that does more routingvar cool = require('cool-ascii-faces'); var express = require('express'); var app = express(); var pg = require('pg'); app.set('port', (process.env.PORT || 5000)); //setting variable "port" to 5000 app.use(express.static(__dirname + '/public')); // views is directory for all template files in project app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); //map URI / to index.ejs in teh sub-directory pages //map URI /nodeMongoDBTest to nodeMongoDBTest.ejs in the sub-directory pages
app.get('/nodeMongoDBTest', function(request, response) {
response.render('pages/nodeMongoDBTest');
});
//when URI /cooll requested call the cool function from the cool module required at top app.get('/cool', function(request, response) { response.send(cool()); }); //when URI /times requested call the inline function which increments #times run app.get('/times', function(request, response) { var result = '' var times = process.env.TIMES || 5 for (i=0; i < times; i++) result += i + ' '; response.send(result); }); //associated listening port to variable "port" which was set above to 5000 app.listen(app.get('port'), function() { console.log('Node app is running on port', app.get('port')); }); |
Decomposing the app.get() call |
What is this request object and response object
req object
The For example:
But you could just as well have:
NOTE: if you want to see the body of the request for printing it out do the following console.log(JSON.stringify(req.body));
if you do the following will brint out a "Object" console.log(req.body);
For example the following handler code: var body = JSON.stringify(req.body); var params = JSON.stringify(req.params); res.send("recieved your request!</br>" + "parameters: " + params +
will produce
|
res object
|
Respond to POST request on the root route (/
), the application’s home page:
app.post('/', function (req, res) {
res.send('Got a POST request')
})
Respond to a PUT request to the /user
route:
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user')
})
Respond to a DELETE request to the /user
route:
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user')
})
In the following example, the handler will be executed for requests to “/secret” whether you are using GET, POST, PUT, DELETE, or any other HTTP request method that is supported in the http module.
app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})
If you want multiple handlers for a Route -- notice the IMPORTANT use of next() --so goes to next handler function
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
var cb2 = function (req, res) {
res.send('Hello from C!')
}
// DEFINE MULTIPLE handler functions for the URI /example/c
app.get('/example/c', [cb0, cb1, cb2])
Routing Patterns
Here are some examples of route paths based on string patterns. This route path will match
This route path will match
This route path will match
This route path will match
Examples of route paths based on regular expressions: This route path will match anything with an “a” in the route name.
This route path will match
|
Routing Parameters
= named URL segments
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.
example 1
To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
|
Response Methods
If none of these methods are called from a route handler, the client request will be left hanging.
Method | Description |
---|---|
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()
. Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: Router() documentation.
Here is an example of chained route handlers that are defined by using app.route()
.
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Add a book')
})
.put(function (req, res) {
res.send('Update the book')
})
express.Router
Use the express.Router
class to create modular, mountable route handlers. A Router
instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.
The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.
Create a router file named birds.js
in the app directory, with the following content:
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
Then, load the router module in the app:
var birds = require('./birds')
// ...
app.use('/birds', birds)
The app will now be able to handle requests to /birds
and /birds/about
, as well as call the timeLog
middleware function that is specific to the route.