npm and package

  1. Introduction to Express

    Express is a fast, open and minimal web development framework based on the Node.js platform. Express is similar to the built-in http module of Node.js, and is specially used to create web servers.

    The essence of Express: it is a third-party package on npm that provides a convenient way to quickly create a web server.

    If you don’t use Express, you need to use the native http module. But the http built-in module is very complicated to use, and the development efficiency is low; Express is further encapsulated based on the built-in http module, which can greatly improve the development efficiency (similar to the relationship between Web API and jQuery).


  2. What Express can do

    For front-end programmers, two common servers are:

    1. Web site server: a server dedicated to providing external Web page resources.
    2. API interface server: a server dedicated to providing API interfaces to the outside world.

    Express can create both types of servers quickly and easily.


  3. Install Express

    Terminal command: npm i express@4.17.1


  4. Create a web server

    1
    2
    3
    4
    5
    6
    const express = require('express')
    const app = express()

    app.listen(80, () => {
    console.log('express server running at http://127.0.0.1')
    })


  1. Listening for GET/POST requests

    Through the app.get() app.post() methods, you can listen to the client’s GET request.

    1
    2
    app.get('Request URL', function(req, res){})
    app.post('Request URL', function(req, res){})


  1. Respond content to client

    The res.send() method can send the processed content to the client. (res.send() default status code is 200)

    1
    2
    3
    4
    5
    6
    app.get('/user', (req, res) => {
    res.send({name:'zs', age:20, gender:'male'})
    })
    app.post('/user', (req, res) => {
    res.send('request succeed')
    })

    res.json() method is the same as res.send() method.

    The difference is that res.send() has a check to check if the incoming object is in string or json format or something else. If it is a json object, it will be returned in json format. This is equivalent to res.send() with the res.json() method built-in. Writing the res.json() method is equivalent to being more explicit, making sure to transfer the object back in json format. When writing, generally choose the res.json() method.


    If you want to return only the response status code, you can use res.sendStatus(), such as:

    1
    res.sendStatus(204)

    Just set the status code without returning:

    1
    res.status(201) //will return a response object
    1
    res.status(201).json({}) //Return the corresponding data at the same time


  1. Return question

    The return in app.get('/', (req, res) => { return }) is a matter of personal code style. In most cases, adding or not adding return is the same. But there is a situation where return must be added, that is, if logic judgments such as if are involved in the callback function to generate branches. In branches, return must be added to each branch to ensure that the code in other branches that follow will not be executed.


    In addition, the following two return methods are also different:

    1
    2
    res.send('Hello world');
    return;
    1
    return res.send('Hello world');

    From the results of running the code, there is no difference between the two writing methods. But if TS type checking is involved, it will result in different types being returned: the first writing method returns undefined, and the second returns the respond type.


  2. How to get data from req

    1. body fetch data

      req.body can retrieve the data in the request body sent by the client. Used for POST, PUT, PATCH requests.

      1
      2
      const {name} = req.body;
      res.send({name}) //This is ES6 abbreviation, it should be res.send({name: name})

    2. query param to get data

      req.query can retrieve the parameters sent by the client to the server from the URL in the form of query string. Defaults to an empty object, used for GET requests.

      1
      2
      3
      4
      5
      app.get('/', (req, res) => { //The client uses ?name=tom&age=20 to send parameters in the form of query strings
      console.log(req.query.name) //Can be accessed with the properties in req.query
      console.log(req.query.age)
      res.send(req.query)
      })

    3. route param (/:id ) to get data (get dynamic parameters in the URL)

      The req.params object can be accessed in the URL through the dynamic parameters matched by : . The string after : can be written arbitrarily, as long as it is reasonable and legal, and the final result returned by the req.params object is {":the latter string":"dynamic parameters requested by the client"} . For example /my/article/:id , where id is not a static value, but a dynamic parameter (dynamically matched parameter value). req.params defaults to an empty object.

      route param can be used for GET, POST, PUT, DELETE four operations, but in most cases it is id.

      1
      2
      3
      4
      app.get('/user/:id', (req, res) => { //The client request is http://127.0.0.1/1, and the id is 1.
      console.log(req.params)
      res.send(req.params) //The returned result is {"id":"1"}
      })

      There can also be multiple dynamic parameters, such as

      1
      app.get('/user/:id/:name', (req, res) => {}

      Server-side requests should be http://127.0.0.1/1/Tom .


Share