Express.js Routes
An Express.js route defines how an application responds when a client sends a request to a specific URL path using a specific HTTP method, such as GET, POST, PUT, or DELETE.
A route normally combines three parts: an HTTP method, a path, and one or more callback functions that process the request and send a response.
app.METHOD(PATH, HANDLER)
appis the Express application.METHODis an HTTP method written in lowercase, such asgetorpost.PATHis the URL path matched by the route.HANDLERis the function that receives the request and response objects.
Why an Express application returns “Cannot GET /”
To see why routes are required, start with a basic Express application.
app.js
var express = require('express')
var app = express()
// start the server
var server = app.listen(8000, function(){
console.log('Listening on port 8000...')
})
This code creates an Express application and starts it on port 8000. Open http://localhost:8000/ in a browser.

The browser displays Cannot GET /. This does not mean that the server failed to start. It means that the application has no route that handles a GET request for the root path /.
The terminal still shows that the application is running.

Define a GET route for the root path
Add a route that handles a GET request for /.
app.get('/', function (req, res) {
res.send('This is a basic Example for Express.js by TUTORIALKART')
})
When Express receives a GET request whose path is /, it runs the callback function. The req object contains request data, while the res object provides methods such as res.send() for returning a response.
The following screenshot shows the structure of a route that responds to a GET request for /hello/.

Create routes for multiple URL paths
The same application can define separate handlers for different paths. Express checks the request method and path, then runs the first matching route.
app.js
var express = require('express')
var app = express()
// route that gets executed for GET request and the request url path '/' or root
app.get('/', function (req, res) {
res.send('Home.')
})
// route that gets executed for GET request and the request url path '/hello/'
app.get('/hello/', function (req, res) {
res.send('Hello page.')
})
// route that gets executed for GET request and the request url path '/bye/'
app.get('/bye/', function (req, res) {
res.send('Bye page.')
})
// start the server
var server = app.listen(8000, function(){
console.log('Listening on port 8000...')
})
Start the Express application.

Now open the following URLs. Entering a URL in a browser sends a GET request by default.
GET request with URL path http://localhost:8000/

GET request with URL path http://localhost:8000/hello/

GET request with URL path http://localhost:8000/bye/

Handle POST, PUT, PATCH, and DELETE routes
Express provides a routing method for each common HTTP method. These methods are useful when building web forms, REST APIs, and CRUD applications.
app.post('/users', function (req, res) {
res.send('Create a user')
})
app.put('/users/:id', function (req, res) {
res.send('Replace user ' + req.params.id)
})
app.patch('/users/:id', function (req, res) {
res.send('Update user ' + req.params.id)
})
app.delete('/users/:id', function (req, res) {
res.send('Delete user ' + req.params.id)
})
A browser address bar is convenient for testing GET routes. For other HTTP methods, use a client such as curl, an API testing application, or frontend JavaScript.
curl -X POST http://localhost:8000/users
curl -X DELETE http://localhost:8000/users/42
Read Express route parameters and query strings
Route parameters capture values that are part of the URL path. A parameter begins with a colon. For example, the route /users/:id matches /users/42, and Express stores 42 in req.params.id.
app.get('/users/:id', function (req, res) {
res.send('User ID: ' + req.params.id)
})
Query strings appear after ? in a URL. For a request such as /search?q=express&page=2, Express makes the values available through req.query.
app.get('/search', function (req, res) {
res.json({
term: req.query.q,
page: req.query.page
})
})
Express route with multiple middleware functions
You can provide one or more functions in a route. Each function is middleware. A middleware function can inspect or modify the request, send a response, or call next() to pass control to the next function. [Reference: Express.js Middleware]
app.js
var express = require('express')
var app = express()
// express route with multiple functions
app.get('/hello/', function (req, res, next) {
res.write('Hello page. ')
next()
}, function(req, res, next){
res.write('Hello again. ')
res.end()
})
// start the server
var server = app.listen(8000, function(){
console.log('Listening on port 8000...')
})
The browser displays the response generated by both functions.

The middleware functions can also be defined separately. This approach makes route logic easier to reuse and test.
var express = require('express')
var app = express()
function hello(req, res, next) {
res.write('Hello page. ')
next()
}
function helloagain(req, res, next){
res.write('Hello again. ')
res.end()
}
// express route with multiple functions
app.get('/hello/', hello, helloagain)
// start the server
var server = app.listen(8000, function(){
console.log('Listening on port 8000...')
})
Group Express routes with express.Router()
As an application grows, keeping every route in app.js becomes difficult to maintain. express.Router() creates a modular route handler that can be mounted under a common path.
routes/users.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('User list')
})
router.get('/:id', function (req, res) {
res.send('User ID: ' + req.params.id)
})
module.exports = router
app.js
var express = require('express')
var usersRouter = require('./routes/users')
var app = express()
app.use('/users', usersRouter)
app.listen(8000)
After mounting the router, its / route responds at /users, and its /:id route responds at paths such as /users/42.
Add a route for unmatched requests
Route order matters. Express processes routes and middleware from top to bottom. Add a fallback handler after all valid routes so unmatched requests return a clear 404 response.
app.use(function (req, res) {
res.status(404).send('Page not found')
})
Do not place this fallback before valid routes, because it would handle every request before those routes can run.
Express.js route questions
What is the difference between app.use() and app.get()?
app.get() handles only GET requests that match its path. app.use() mounts middleware or a router and can run for multiple HTTP methods. Its path matching is also commonly used as a prefix.
Why does an Express route not run?
Check the HTTP method, URL path, route order, and whether an earlier middleware function ends the response without calling next(). Also confirm that the server was restarted after the code changed.
How do I get a value from an Express route URL?
Use a route parameter such as /users/:id and read it from req.params.id. Use req.query for values supplied in a query string.
Can one Express route run multiple functions?
Yes. Pass the functions in order and call next() when a function should transfer control to the next one. A function that sends or ends the response should not call next() unless another handler is intentionally expected to run.
Express.js routes editorial QA checklist
- Confirm that each sample route uses the intended HTTP method and URL path.
- Verify that every middleware chain either sends a response or calls
next(). - Check that parameter examples read values from
req.paramsand query examples usereq.query. - Keep the 404 fallback after all valid application routes.
- Test non-GET examples with an HTTP client instead of relying on the browser address bar.
Express.js routes summary
In this Express.js Tutorial, you learned how Express.js routes match HTTP methods and URL paths, how route handlers use req and res, how to work with route parameters and query strings, how to chain middleware functions, how to organize routes with express.Router(), and how to return a 404 response for unmatched requests.
TutorialKart.com