current position:Home>Express request methods -- get, post, patch, delete

Express request methods -- get, post, patch, delete

2021-08-27 03:18:27 Mannqo

This is my participation 8 The fourth of the yuegengwen challenge 16 God , Check out the activity details :8 Yuegengwen challenge

mention node I'll think of express, Just started learning express It's still a little difficult , stay b I've been looking for a lot of courses to see , Learn from the basics step by step .


One 、 Introduce Express

Express Have a rich foundation API Support , And common HTTP Auxiliary program , For example, redirection 、 Cache, etc ; It has powerful routing function 、 Flexible middleware ; High performance and stability ;Express Only... Is provided web Basic functions of development , It passes through middleware The method integrates many external plug-ins to handle HTTP request .

  • body-parser: analysis HTTP Request body
  • compression: Compress HTTP Respond to
  • cookie-parser: analysis cookie data
  • cors: Handle cross domain resource requests
  • morganHTTP Request logging
  • ...

Express Middleware for Express Itself becomes more flexible and simple , The disadvantage is that although some middleware packages solve almost all problems or requirements across domains , But choosing the right package can sometimes be a challenge .Express incorrect Node.js Second abstraction of existing features , Just expand on it web The basic functions required by the application ;

  • Internal use is still HTTP modular
  • The request object inherits from :http.IncomingMessage
  • The response object inherits from :http.ServerResponse

There are many popular frameworks based on Express, such as LoopBackSailsNextJs

Express Of Hello World

introduce express modular , Create a server , And then on the browser get Request to respond ;

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

Two 、 Routing basis

Routing is to determine how an application responds to a client's request for a particular endpoint , The specific endpoint is URI( Or the path ) And specific HTTP Request method (get,post etc. ). Each route can have one or more handler functions , These functions execute when matching the route ; Adopt the following structure to realize :( As above get request )

app.method(path, handle); 
 Copy code 
  • app yes Express example
  • method It's lowercase HTTP Request method
  • path It's the path on the server
  • handle Is the function performed when the route matches

Requests and responses

Express The application uses the parameters of the route callback function :request and response Object to process the corresponding request and response data ;

  • Request object : Get information about the request ; Inherited from http.IncomingMessage

  • stay express Through req.query Get request parameters ; Specific reference Express - API file

  • The 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 status and respond 
     Copy code 

3、 ... and 、 Four ways to request

When we write each route , Generally, you have to read some content and respond to the browser , For example, we put the data in db.json In the document , And then again app.js Used in documents fs.readFile() Reading data ; Here we can put app.js Some frequently used methods used in are written in another file db.js Inside , such as 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 code 

1. get request

After encapsulation, in app.js Pass through await getDb() You can get the corresponding data content ;( Remember async); If it doesn't exist, go back 404 Status code , If found, respond to the found data content ; use try...catch To avoid a small number of errors that make the whole program unable to run ; Be careful :req.params For request parameters

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

2. post request

  • Configure parsing form request body

    application/jsonapp.use(express.json()); take json Data in the form of js object ;


  • post We usually use it to submit data , Here we need to use fs.writeFile;

  • similarly , Write the method in db.js In file ; When writing data , If we want to make json If the data in appears to be formatted , With (db, null, ' ') Is a parameter ;

    exports.saveDb = async () => {
        const data = JSON.stringify(db, null, ' ');  //  Give Way db.json The data in has a format 
        await writeFile(dbPath, data);
     Copy code 
  • Later on app.js Process the data , If todo.title If it doesn't exist, go back 404, If it exists, the data will be added push To the corresponding array (todo) in , Write data after data 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]; = lastTodo ? + 1 : 1;
        await saveDb(db);
    } catch (err) {
            error: err.message
     Copy code 

3. patch request

  • First pass req.body Get form data :const todo = req.body;

  • Find the task item to modify , If you don't find it, you don't have to change it , Go straight back to 404 that will do ; If found, modify the data ,

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

    Be careful :Object.assign The method is shallow copy , The first parameter is the target object , Later parameters are all source objects ; If the target object has the same property as the source object , Or multiple source objects have properties with the same name , Then the following properties will overwrite the previous properties ;

4. delete operation

  • Find the item to delete

    const todoId = Number.parseInt(;
    const db = await getDb();
    const index = db.todos.findIndex(todo => === todoId);
     Copy code 
  • findIndex This API Find return index , If you don't find it, go back -1; Once found, delete this data ;

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

I've always been curious about how the browser and server connect , Finally learned express Understand the process

copyright notice
author[Mannqo],Please bring the original link to reprint, thank you.

Random recommended