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

Chainable route methods

Route methods can be chainable using app.route(path) because the path is specified for a single location. This is probably the best approach when dealing with multiple route methods because, besides making the code more readable and less prone to typos and redundancy, it allows to work with multiple route methods at the same time.

  1. Create a new file named 3-chainable-routes.js
  2. Initialize a new ExpressJS application:
      const express = require('express') 
      const app = express() 
  1. Chain three route methods using the route method:
      app 
      .route('/home') 
      .get((request, response, nextHandler) => { 
          response.type('text/html') 
          response.write('<!DOCTYPE html>') 
          nextHandler() 
      }) 
      .get((request, response, nextHandler) => { 
          response.end(` 
          <html lang="en"> 
              <head> 
              <meta charset="utf-8"> 
              <title>WebApp powered by ExpressJS</title> 
              </head> 
              <body role="application"> 
                  <form method="post" action="/home"> 
                      <input type="text" /> 
                      <button type="submit">Send</button> 
                  </form> 
              </body> 
          </html> 
          `) 
      }) 
      .post((request, response, nextHandler) => { 
          response.send('Got it!') 
      }) 
  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 3-chainable-routes.js
  1. To see the result, open a new tab in your web browser and visit:
      http://localhost:1337/home