ExpressJS Routing - ExpressJS

How is the basic routing in Express?

The following function signature is used to define routes in an express application:

app.METHOD(PATH, HANDLER)

  • METHOD is any one of the HTTP request method (get, set, put, delete). An alternate method called all exists that executes independent of the request type.
  • Path is the path at which the request runs.
  • Handler is a callback function that executes when a matching request type is found on the relevant route.

For example,

Run the application and go to localhost:3000/hello. The server receives a get request at route "/hello" and the Express app executes the callback function attached to this route and sends "Hello World!" as the response.

Routing hello


Example for multiple methods at the same route

To test this request, open up your terminal and use cURL to execute the following request

A special method, all, handles all types of http methods at a particular route using the same function. To use this method, try the following:

This method is generally used for defining middleware.

Routers

Routers simplifies the maintenance of the code by helping in seperating out concerns and keep relevent portions of code together. Always define the routes relating to an entity in a single file and include it using above method in your index.js file.

Let us use Express.Router to separate out routes from main index.js file. Create a new file called things.js and type the following in it.

Now to use this router in our index.js, type in the following before the app.listen function call.

The app.use function call on route '/things' attaches the things router with this route. Now whatever requests the app gets at the '/things', will be handled by things.js router. The '/' route in things.js is actually a subroute of '/things'. Visit localhost:3000/things/ -

things

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

ExpressJS Topics