CRUD operations using ExpressJS' route methods

ExpressJS' router has equivalent methods to handle HTTP methods. In other words, the HTTP methods POST, GET, PUT, and DELETE can be handled by this code:

      /* Add a new user */ 
      app.post('/users', (request, response, next) => { }) 
      /* Get user */ 
      app.get('/users/:id', (request, response, next) => { }) 
      /* Update a user */ 
      app.put('/users/:id', (request, response, next) => { }) 
      /* Delete a user */ 
      app.delete('/users/:id', (request, response, next) => { })  

It's good to think of every URL as a noun and because of that a verb can act on it. In fact, HTTP methods are also known as HTTP verbs. If we think about them as verbs, when a request is made to our RESTful API, they can be understood as:

  • Post a user
  • Get a user
  • Update a user
  • Delete a user.

In the MVC (model-view-controller) architectural pattern, controllers are in charge of transforming input to something a model or view can understand. In other words, they transform input into actions or commands and sends them to the model or view to update accordingly.

ExpressJS' route methods usually act as controllers. They just get input from a client such as a request from the browser, and then converts the input to actions. These actions are then sent to the model, which is the business logic of your application, such as a mongoose model, or to a view (a ReactJS client application) to update.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.123.217