MERN Quick Start Guide
上QQ阅读APP看书,第一时间看更新

Route handlers

Route handlers are callback functions that accept three arguments. The first one is the request object, the second one is the response object, and the last one is a callback, which passes the handler to the next request handler in the chain. Multiple callback functions can be used inside a route method as well.

Let's see a working example of how we could write route handlers inside route methods:

  1. Create a new file named 2-route-handlers.js
  2. Include the ExpressJS library, then initialize a new ExpressJS application:
      const express = require('express') 
      const app = express() 
  1. Add two route methods to handle a request in the same path "/one". Use the type method of the response object to set the content type of the response sent to the client to text/plain. Using the write method send partial data to the client. To finalize sending data, use the end method of the response object. Calling nextHandler will pass the handler to the second handler in the chain:
      app.get('/one', (request, response, nextHandler) => { 
          response.type('text/plain') 
          response.write('Hello ') 
          nextHandler() 
      }) 
      app.get('/one', (request, response, nextHandler) => { 
         response.status(200).end('World!') 
      }) 
  1. Add a route method to handle a request in the path "/two". Two route handlers are defined inside the route method to handle the same request:
      app.get('/two', 
          (request, response, nextHandler) => { 
             response.type('text/plain') 
             response.write('Hello ') 
             nextHandler() 
         }, 
          (request, response, nextHandler) => { 
             response.status(200).end('Moon!') 
         } 
      ) 
  1. Use the listen method to accept new connections on port 1337:
      app.listen( 
         1337, 
         () => console.log('Web Server running on port 1337'), 
     ) 
  1. Save the file
  2. Open a Terminal and run:
    node 2-route-handlers.js  
  1. To see the result, open a new tab in your web browser and visit:
 http://localhost:1337/one
 http://localhost:1337/two