This is the 16th day of my participation in the August Text Challenge.More challenges in August

When it comes to Node, express comes to mind. At the beginning, it was a little difficult to learn Express. I found many courses in STATION B and started to learn from the basics step by step.

Express

I. Introduction to Express

Express has rich base API support and common HTTP helpers such as redirection, caching, and so on. Have powerful routing function, flexible middleware; High performance and stability; Express provides only the basics of Web development, integrating many external plug-ins to handle HTTP requests through a middleware approach.

  • body-parser: parsingHTTPRequest body
  • compression: compressionHTTPThe response
  • cookie-parser: Parses cookie data
  • cors: Processes cross-domain resource requests
  • morgan:HTTPRequest logging
  • .

The middleware of Express makes Express itself much more flexible and simple, but the downside is that while there are middleware packages that cross domains to address almost any problem or requirement, picking the right package can sometimes be a challenge. Express does not abstract the existing features of Node.js, but merely extends the basic functionality required by Web applications.

  • For internal use orHTTPThe module
  • Request objects inherit from:http.IncomingMessage
  • The response object inherits from:http.ServerResponse

Many popular frameworks are based on Express, like LoopBack, Sails, and NextJs

Express theHello World

The express module is introduced to create a server that responds to browser GET requests.

const express = require('express');
const app = express();
app.get('/'.(req, res) = > {
    res.send('Hello World! ');  // Send the response
})
app.listen(3000);
Copy the code

2. Routing basis

Routing is about determining how an application responds to a client’s request to a particular endpoint, which is a URI(or path) and a particular HTTP request method (GET, POST, and so on). Each route can have one or more handler functions that are executed when the route is matched; This is implemented using the following structure :(get request above)

app.method(path, handle); 
Copy the code
  • appIs Express instance
  • Method is lowercaseHTTPRequest method
  • Path is the path on the server
  • Handle is a function performed when routing matches

Request and response

The Express application uses the parameters of the routing callback function: request and Response objects to process the corresponding request and response data;

  • Request object: gets information about the request. Inherited from HTTP. IncomingMessage

  • In Express, request parameters can be obtained via req.query; Refer to the Express-API documentation for details

  • Response object: used to process requests and send responses; Inherited from HTTP. ServerResponse

    res.cookie('foo'.'bar');
    res.status(201).send({foo: 'bar'});    // Set the state and respond
    Copy the code

Three or four ways to request

When we write each route, we usually need to read some content and then respond to the browser. For example, we put the data in the db.json file, and then read the data in the app.js file with fs.readfile (). Here you can write some of the frequently used methods used in app.js in a separate file called db.js, such as the fs.readfiles () method;

const fs = require('fs')
const { promisify } = require('util')
const path = require('path');
const readFile = promisify(fs.readFile);
const dbPath = path.join(__dirname, './db.json');  // Absolute path
exports.getDb = async() = > {const data = await readFile(dbPath, 'utf-8');
    return JSON.parse(data);
}
Copy the code

1. Get request

After encapsulation, we can obtain the corresponding data content in app.js by await getDb(); (Remember async); Returns a 404 status code if it does not exist, and responds to the data found if it does; Using a try… Catch is to avoid a small number of errors that cause the entire program to fail; Note: req.params is the request parameter

const { getDb } = require('./db')
app.get('/todos/:id'.async (req, res) => {
    try {
        const db = await getDb();
        const todo = db.todos.find(todo= > todo.id === Number.parseInt(req.params.id));
        if(! todo) {return res.status(404).end(); }
        res.status(200).json(todo);
    } catch (err) {
        res.status(500).json({
            error: err.message
        })
    }
})
Copy the code

2. A post request

  • Configure the parse form request body

    Application/json: app. Use (express. Json ()); Convert json data to JS objects;

    Application/x – WWW – form – urlencoded: app. Use (express. Urlencoded)

  • Post is used to submit data, in this case fs.writefile;

  • Again, write the methods in the db.js file; (db, null, “”);

    exports.saveDb = async() = > {const data = JSON.stringify(db, null.' ');  // Format the data in db.json
        await writeFile(dbPath, data);
    }
    Copy the code
  • If todo.title does not exist, 404 will be returned. If it does exist, the added data will be pushed to the corresponding array (TODO), and data will be written after submission.

    try {
        if(! todo.title) {return res.status(404).json({ error: 'The field title is required'})}const db = await getDb();
        const lastTodo = db.todos[db.todos.length - 1];
        todo.id = lastTodo ? lastTodo.id + 1 : 1;
        db.todos.push(todo);
        await saveDb(db);
        res.status(200).json(todo);
    } catch (err) {
        res.status(500).json({
            error: err.message
        })
    }
    Copy the code

3. The patch request

  • First get the form data from req.body: const todo = req.body;

  • Search for the task item to modify, if not found, no need to change, directly return 404 can be; If you find it and you modify it,

    const db = await getDb();
    const ret = db.todos.find(todo= > todo.id === Number.parseInt(req.params.id));
    if(! res) {return res.status(404).end();
    }
    Object.assign(ret, todo);
    await saveDb(db);
    res.status(200).json(ret);
    Copy the code

    Note: Object.assign is a shallow copy. The first argument is the target Object, and the following arguments are the source Object. If the target object has an attribute with the same name as the source object, or multiple source objects have an attribute with the same name, the later attribute overrides the previous one;

4. The delete operation

  • Find the item to delete

    const todoId = Number.parseInt(req.params.id);
    const db = await getDb();
    const index = db.todos.findIndex(todo= > todo.id === todoId);
    Copy the code
  • The findIndex API returns the index, or -1 if no index is found; Delete the data after it is found;

    if (index === -1) { return res.status(404).end(); }
    db.todos.splice(index, 1);
    await saveDb(db);
    res.status(200).end();
    Copy the code

I have always been curious about how the browser and server are connected. Finally, I learned Express and learned this process