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

Route methods

These are derived from HTTP verbs or HTTP methods. A route method is used to define the response that an application will have for a specific HTTP verb.

ExpressJS route methods have equivalent names to HTTP verbs. For instance: app.get() for the GET HTTP verb or app.delete() for the DELETE HTTP verb.

A very basic route can be written as the following:

  1. Create a new file named 1-basic-route.js
  2. Include the ExpressJS library first and initialize a new ExpressJS application:
      const express = require('express') 
      const app = express() 
  1. Add a new route method to handle requests for the path "/". The first argument specifies the path or URL, the next argument is the route handler. Inside the route handler, let's use the response object to send a status code 200 (OK) and text to the client:
      app.get('/', (request, response, nextHandler) => { 
          response.status(200).send('Hello from ExpressJS') 
      }) 
  1. Finally, 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 the following command:
     node 1-basic-route.js 
  1. Open a new tab on your browser and visit localhost on port 1337 in your web browser to see the results:
      http://localhost:1337/

For more information about which HTTP methods are supported by ExpressJS, visit the official ExpressJS website at https://expressjs.com/en/guide/routing.html#route-methods.