introduce

Express is known for its simplicity, ease of use, and ability to quickly create powerful apis. This article is my notes on learning it, including basic usage and techniques. Express official document.

basis

const express = require('express')

const app = express()
const port = 8080

app.use('/'.(res,req) = >{ // Return 'hello world' when accessing the root directory '/'
  res.send('hello world')})/** * the callback will not be executed when it calls '/ API 'because the '/' in the preceding '/ API' will be matched by */  
app.use('/api'.(res,req) = >{ 
  res.send('hello api')
})

app.listen(port, () = > {
  console.log(`running on port ${port}`)})Copy the code

App.use is the method of using middleware, and the callback function in it is called middleware.

The middleware

basis

app.use('/api'.(req, res, next) = > {
    console.log(0)
    next()     // After the previous function is executed, the next middleware cannot execute until next is executed
  }, (req, res, next) = > {
    console.log(1)
    next()
  }, (req, res) = > {
    console.log(2)})Copy the code

Here is the equivalent:

const middleware = [
  (req, res, next) = > {
    console.log(0)
    next()
  },
  (req, res, next) = > {
    console.log(1)
    next()
  },
  (req, res) = > {
    console.log(2)
  },
]

app.use('/api',middleware)
Copy the code

Express matches the corresponding function based on the URL accessed. If there are multiple functions, they are executed in written order, as if they were queued.

routing

Basic usage

Routing is also called routing middleware. Routing middleware matches whatever path it writes (which can be regex), unlike use.

router.get('/index'.(req,res) = >{ // 'index' can be a re
  res.send('<h1>index page.</h1>')})Copy the code

As you can guess from the above method, besides get, there should be post, PUT and other methods. By jumping to the definition, you can see that this is true. Here is the interface in the source code:

export interface IRouterMatcher<
    T,
    Method extends 'all' | 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head' = any
>
Copy the code

You don’t have to be familiar with TypeScript to guess that there are multiple methods that correspond to how requests are made, except for the all. The all method can also look at the word business and match the way all HTTP requests are made. Commonly used to add middleware, as follows:

app.all('/auth'.function (req, res, next) {
  // Verify any request to access the Auth interface
  next() // Proceed with the following code
})
Copy the code

Split the file

Generally speaking, an application has many interfaces. If they are all written in a file, it is difficult to maintain them. The routing section can be unwrapped as follows, and here is the main file (/server.js) :

const express = require('express')

const app = express()
const router = require('./router') // The route file is in the router folder of the same directory as /router/index.js
const port = 8080

app.use(router) // No write path Using middleware handles all requests, but does not affect other routing paths.

app.listen(port, () = > {
  console.log(`running on port ${port}`)})Copy the code

Here is the routing file (/router/index.js) :

const express = require('express')

const router = express()

router.get('/index'.(req,res) = >{
  res.send('<h1>index page.</h1>')})module.exports = router
Copy the code

Gets the parameters from the front end

There are two ways:

  • throughreq.query
  • throughreq.params
router.get('/index/:id'.(req, res) = > {
  const query = req.query
  constparams = req.params res.json({ ... query, ... params })// Return all the attributes in query and params as json
})
Copy the code

Here is what happens when the code above requests the URL:

Split controller

When routing starts to multiply, the code looks awkward. Split controller (the method that corresponds to routing) as follows:

// Routing file
const express = require('express')

const router = express()
const { list } = require('.. /controller')

router.get('/list',list) 
Copy the code

The controller is as follows:

const list = (req,res,next) = >{
  res.json([
    {name: 'bob'.age: 18},
    {name: 'jerry'.age: 19})}exports.list = list
Copy the code

The current directory structure is as follows: