Introduction to the Node. Js

What is a Node. Js

Node.js is a JavaScript runtime environment based on Chrome V8 engine.

Node.js provides the necessary environment for JavaScript code to run properly.

Node.js’ official website: nodejs.org/zh-cn/

Node.js In Chinese: nodejs.cn/api/

The difference between NodeJS and browsers

① The browser is the front-end running environment of JavaScript.

Node.js is a back-end environment for JavaScript.

(3) Node.js cannot call built-in apis such as DOM and BOM.

What can Node.js do

As a JavaScript runtime environment, Node.js provides only basic functionality and apis. However, many powerful tools and frameworks have sprung up based on the basic capabilities provided by Node.js, so learning Node.js can help front-end programmers do more jobs and positions:

① Based on the Express framework (www.expressjs.com.cn/), you can quickly build Web applications

(2) Based on Electron framework (electronjs.org/), can build a cross-platform table…

Restify framework (restify.com/) allows you to quickly build API projects

④ Read and write and operate database, create practical command line tools to assist front-end development, etc…

Install the Node.js environment

If you want to run Javascript code through Node.js, you must have the Node.js environment installed on your computer.

Terminal Use

Terminal (English: Terminal) is specially designed for developers and is used to realize human-computer interaction.

Nodejs is different from ordinary programs. You need to use the node command in the terminal to use nodejs.

Use any terminal (e.g. CTRL + ~ in vscode)

Install nodejs

Enter node -v on the terminal. If the node. js version is displayed, the installation is successful

Common Terminal Commands

  • cdChange the directory
  • cd..Go back to the previous directory directlycdGo to the default directory
  • pwdThe current directory path is displayed
  • ls(llList all files in the current directory, butllListed in more detail
  • touchCreate a new file in the current directory (for Powershell)new-item)
  • rmDelete a file
  • mdCreate a new folder under the current directory
  • rm -rDelete a folder (extra f empties the entire computer!!)
  • mvMove file (mv 1.html num Move file 1 to num folder, provided they are at the same level)
  • resetReinitialize terminal/clear screen (PowerShell unavailable)
  • clearClear the screen
  • historyViewing command History
  • helphelp
  • exitexit
  • #Said annotation

Nodejs is used for basic purposes

In Node.js you need a terminal to execute JavaScript code

① Open the terminal

② Enter the path of the node.js file to execute the code stored in the.js file

Create the js file helloworld.js

Write nodejs content: console.log(‘hello nodejs’)

Open a terminal

Run the node helloworld.js command

Common Shortcut keys

On the Windows CLI, you can use the following shortcut keys to improve the efficiency of cli operations: 1 ↑ to locate the last command, 2 TAB to quickly complete the path, and 3 Esc to clear the entered commands

Node Built-in module

Global module (Node’s global module)

Note: Global does not need to be imported, but used directly

  1. The console. The log () to print
  2. SetTimeout and setInterval, delayers and timers
  3. __dirName Absolute path of the current folder

Fs module

In NodeJS, the FS module is provided, which is the core module of Node

nodejs.cn/api/fs.html

Note:

  1. All modules need to be loaded except for the contents in the Global module, which can be used directly.
  2. The FS module is not global and cannot be used directly. So you need to import it to use it.
// Import the fs module before using it
const fs = require('fs')
Copy the code

Read the file

Syntax: fs.readfile (path[, options], callback)

// Parameter 1: file path
Parameter 2(optional) : encoding, if set, returns a string, if not set, returns a buffer object
// Parameter 3: callback function
fs.readFile('data.txt'.'utf8'.(err, data) = >{
  if(err) return console.log('File reading failed',err) 
  console.log('File read successfully',data)
})
Copy the code

About Buffer objects

1.Buffer objects are used by Nodejs to process binary data.2.In fact, any data at the bottom of the computer is binary data, because the computer only knows binary data.3.Therefore, reading any file will return binary data, namely Buffer objects4.A Buffer object can be converted to a string by calling toString().Copy the code

Written to the file

Syntax: fs.writefile (file, data[, options], callback)

// Parameter 1: path to the file (if the file does not exist, it will be created automatically)
// Parameter 2: the content of the file to be written (note: the content to be written overwrites the previous content)
// Parameter 3: the callback function after writing the file
fs.writeFile('2.txt'.'hello world'.err= >{
  if(err) return console.log('Failed to write file', err)
  console.log('Write file successful')})Copy the code

Additional documents

Syntax: fs.appendFile(path, data[, options], callback)

// Parameter 1: path to the file (if the file does not exist, it will be created automatically)
// Parameter 2: appending file content (note: writing content overwrites previous content)
// Parameter 3: the callback function after appending the file
fs.appendFile('2.txt'.'I'm an addendum'.err= >{
  if(err) return console.log('Failed to append file contents',err)
  console.log('File content appended successfully')})Copy the code

Fs module-path dynamic Mosaic problem

When using the FS module to manipulate files, if the operation path provided is./ or.. / when relative paths start, it is easy to have dynamic path concatenation errors. Reason: At runtime, the code dynamically concatenates the full path to the file being manipulated from the directory in which the node command was executed. Solution: When using fs module to manipulate files, provide absolute path directly, do not provide./ or.. / starts relative paths to prevent dynamic path concatenation problems.

Note: use **__dirname to get the absolute path to the current file folder **

const fs = require('fs');
// Concatenate the absolute path to the file to read
const filepath = __dirname +'/hello.txt'
fs.readFile(filepath, 'utf-8'.(err, data) = > {
	if(err) return console.log('File reading failed',err) 
	console.log('File read successfully',data)
})
Copy the code

Path Path module

The path module is officially provided by Node.js to handle paths. It provides a set of methods and properties to meet the user’s path handling requirements.

// Import the fs module before using it
const path = require('path')
Copy the code

Path joining together

Syntax for path.join()

Using the path.join() method, you can concatenate multiple path fragments into a complete path string in the following syntax:

path.join(pathA,pathB,pathC...) // Returns a string
Copy the code

Example code for path.join()

const path = require('path');

console.log( path.join('a'.'b'.'c'))// a/b/c
console.log( path.join('a'.'/b/'.'c'))// a/b/c
console.log( path.join('a'.'/b/'.'c'.'index.html'))// a/b/c/index.html
console.log( path.join('a'.'b'.'.. /c'.'index.html'))// a/c/index.html
console.log(__dirname)	// The global variable that comes with node, which represents the absolute path of the current JS file

// The absolute path to the concatenated file
console.log( path.join(__dirname, 'grades. TXT'))Copy the code

Gets the file name in the path

The syntax of path.basename()

Use path.basename() to get the name of the file (with or without an extension, which is the same as the path itself)

path.basename(pathA)
Copy the code

Example code for path.basename()

console.log( path.basename('index.html'))// index.html
console.log( path.basename('a/b/c/index.html'))// index.html
console.log(path.basename('/a.jpg')) // a.jpg
Copy the code

Gets the file extension in the path

The syntax of path.extname()

The path.extname() method is used to obtain the extension part of the path in the following syntax:

path.extname(pathA)
Copy the code

Example code for path.extName ()

Using the path.extName () method, you can get the extension part of the path

// Find the character after the last dot in the string
console.log( path.extname('index.html'));// .html
console.log( path.extname('a.b.c.d.html'));// .html
console.log( path.extname('asdfas/asdfa/a.b.c.d.html'));// .html
console.log( path.extname('adf.adsf'));// .adsf
Copy the code

The HTTP module

The HTTP module is an official node.js module used to create web servers.

Create a basic Web server

Basic steps for creating a Web server

① Import the HTTP module ② create a Web server instance ③ bind request events to the server instance and listen for client requests ④ Start the server

Creating a Web implementation

// 1. Import HTTP module
const http = require('http');
2. Create a server
const server=http.createServer()
// 3. Start the service and listen
server.listen(3000.() = >{
    console.log('You're hot.');
})
// 4. Listen for user requests
server.on('request'.(req,res) = >{
    // Set the character set to UTF-8 (so that Chinese can be parsed) on the first line
    res.setHeader('content-type'.'text/html; charset=utf-8')

    console.log('Mosimosi');
    // console.log(req.headers);
    console.log(req.method);    // Request mode
    console.log(req.url);    // The requested address

    // res.statuscode =404 // set the statusCode
    // res.statusMessage='not find' // Set the status information
	// res.write('abc')
    // res.end is written at the end
    res.end('< h1 > < / h1 > cattle')})Copy the code

The port number

A port number in a computer is just like a house number in real life. By using the number of doors, the delivery guy can deliver food to you in any of the many rooms in the building. In the same way, hundreds of Web services can run on a single server. In this case, the network request sent by the client can be accurately sent to the Web service corresponding to the port number for processing.

Request Object details

Document address: nodejs.cn/api/http.ht…

Common attributes:

Headers: indicates all request headers. Method: indicates the request method. Url: indicates the request addressCopy the code

Note: There may be two requests when sending a request, because Google Chrome automatically adds a request for favicon.ico.

Description of response object

Document address: nodejs.cn/api/http.ht…

Common properties and methods:

Res.setheader (name, value) sets the response header, for example, content-type res.writeHead(statusCode, statusMessage, options) sets the response header. You can also set the status code and status information. Res. statusCode: indicates the statusCode of the response200 404 500Res. statusMessage: The status of the response, OK Not Found, is automatically set according to statusCode. Res.write (data): Sends the response body to the browser, which can be called multiple times to provide a continuous request body res.end() to inform the browser that all response headers and response bodies have been sent, that is, the server considers it completed. Res.end (data) ends the request and responds with a piece of content equivalent to res.write(data) + res.end()Copy the code

Solve the problem of Chinese garble

When res.end() is called to send Chinese content to the client, garbled characters will appear. In this case, you need to manually set the encoding format of the content:

res.setHeader('Content-Type'.'text/html; charset=utf-8');
Copy the code

Respond to different HTML content based on different URLS

const http = require('http')

const server = http.createServer()

server.listen(3000.() = > console.log('my server running'))

server.on('request'.(req, res) = > {
    res.setHeader('Content-Type'.'text/html; charset=utf-8')
    const url = req.url // Get the requested URL
    if (url === '/' || url === 'index.html') {
        res.end('< h1 > home page < / h1 >')}else if (url === '/about.html') {
        res.end('

About us

)}else { res.end('<h1>404</h1>')}})Copy the code

Implement a static WEB server

Server Response Front page

  • Note: the URL entered in the browser is only an identifier and does not match the directory on the server. That is: what is returned is determined by the server logic
server.on('request'.function(req, res) {
  var url = req.url
  if(url === '/') {
    fs.readFile('./index.html'.function(err, data) {
      if(err) {
        return res.end('The resource you accessed does not exist ~')
      }

      res.end(data)
    })
  }
})
Copy the code

According to the different URL, the response to different files

Content-type Specifies the MIME type

  • MIME(Multipurpose Internet Mail Extensions) is a standardized way to express the nature and format of a document
  • Browsers typically use MIME types, not file extensions, to determine how to process documents; It is therefore important that the server append the correct MIME type to the header of the response object
  • The MIME type

Generic handling of static resources

Generic handling of MIME types – MIME modules

  • Gets the MIME type of a file
  • Installation:npm i mime
const mime = require('mime')

// Get the MIME type of the path
mime.getType('txt')                    / / ⇨ 'text/plain'
// Get file name extension according to MIME
mime.getExtension('text/plain')        / / ⇨ 'TXT'
Copy the code

Initial use of NPM

introduce

NPM (Node Package Manager) Node package manager.

What is a bag? A package is a module.

The NPM tool is already installed on your computer when you install Node.

Run the NPM -v command. If the version number is displayed, the installation is successful.

role

NPM is a tool for managing node modules.

Third-party modules:

  • Non-built-in modules that cannot be used after Node is installed can be used only after being downloaded and installed from the Internet
  • Third-party modules are modules written by individuals, companies and organizations and posted online for us to use

Initialize the

The NPM tool must be initialized before it can be used.

NPM init -y // (or NPM init) higher versions omit this stepCopy the code

After initialization, a package.json file is generated in the project directory.

Third-party modules

A module that does not come with Node.

It is a module written by others, and then published to the NPM website, we can use the NPM tool to download and install modules written by others.

The third party module is based on the node core module, encapsulated, to achieve a lot of very convenient, quick and simple methods.

Currently, the NPM website contains more than 600,000 third-party modules.

Install and uninstall project modules

Download and install third-party modules

NPM install NPM installCopy the code

Uninstall the module

NPM UN module name // NPM uninstall module nameCopy the code

Description of project modules

  • Download the installed module and store it in the current foldernode_modulesA file is also generated to record the downloadpackage-lock.json
  • Where can I use the downloaded module
    • In the current folder
    • Subfolders in the current folder
    • Subfolders in subfolders of the current folder
    • .
  • How to use third-party modules
    • As with built-in modules, you need to userequireLoad module
    • Call the methods provided by the module to do the work (generally good modules use documentation)

Demo download and install third-party modules

Here’s a module that handles dates and times — moment

momentjs.cn/

Download and install the moment module

npm init -y
npm i moment
Copy the code

The demo uses the moment module to handle time

// Load the module
const moment = require('moment');

console.log(moment().format('YYYY-MM-DD hh:mm:ss'));
// Official website: http://momentjs.cn
Copy the code

Global module

  • Globally installed modules cannot be loaded and used by require().

  • Globally installed modules are generally commands or tools.

  • Installation method: Add -g after the command to install the module

    NPM I -g // (NPM I -g)Copy the code
  • View globally installed modules

    npm list -g --depth 0
    Copy the code
  • Unload method (also one more -g)

    NPM UN Module name -gCopy the code
  • Globally installed modules on system disk (drive C)

    • Through the commandnpm root -gYou can view the global installation path
  • You can use sudo NPM I XXX -g to install the MAC

Install the Nodemon module globally

npm i nodemon -g  
Copy the code

Functions of Nodemon: Instead of the Node command to start the service, nodemon will automatically restart the service for us after changing the code

An error may occur when nodemon is run:

The solution:

  • The administratorTo open Windows PowerShell
  • performset-ExecutionPolicy RemoteSignedCommand to change the execution policy
  • In the options that appear, replyA, it was all about

If a policy override error continues, type the following code:

Set-ExecutionPolicy "RemoteSigned" -Scope Process -Confirm:$false
Set-ExecutionPolicy "RemoteSigned" -Scope CurrentUser -Confirm:$false
Copy the code

Reference docs.microsoft.com/zh-cn/archi…

The difference between local and global installation

There are two ways to install NPM packages: local installation and global installation. Which way to install depends on how you use the package.

  1. The local installation
  • Want to use the package we use, install into the current local project use
  • Example: NPM I jquery, NPM I moment
  • Requirement: Execute the install command (NPM I moment) location, must be executed under the current project
  • Package location: locally installed package => node_modules under the current project
  • Use the package:const moment = require('moment') , const $ = require('jquery')
  1. Global installation
  • Note: If you want to use a package/library as a tool, use global installation

  • Example: NPM I-G Nodemon

  • Requirements: Can be anywhere, can execute the command

  • Package Location: C:\Users\ User name \AppData\Roaming\ NPM

  • Use package: use in terminal command line, not in code

Dependencies that

1. Function: Save the records of dependent packages.

2, if you see that there is no node_modules directory in our project, but package.json. That our project is complete. NPM I looks for dependencies in package.json and installs all dependencies in it

3. Run the NPM I command in the package.json directory.

Changing the Mirror Source

Mirror source, is the download and installation of third-party modules of the website.

The third-party modules we downloaded were all downloaded from the foreign NPM master station, and the speed was relatively slow.

Taobao has made a backup of the third-party module on NPM in China, that is to say, we can download the third-party module from China.

In addition to Taobao, there are many other mirror sources.

Simple method to change the mirror source:

  • Install NRM modules globally
    • NRM is used to manage image sources
    • npm i nrm -g
  • The use of NRM
    • nrm lsUsing this command, you can view available mirror sources
    • nrm use taobao, switch the download module to Taobao website

NRM installation error:

Solutions:

Open C:\Users\Administrator\AppData\Roaming\ NPM \node_modules\ NRM \cli.js:17:20(Make hidden folder visible)

Change the code as follows (32-bit Windows uses USERPROFILE instead of HOME):

modular

Modularization refers to the process of solving a complex problem by dividing the system into several modules layer by layer from top to bottom. For the whole system, modules are units that can be combined, decomposed and replaced.

A module is simply a separate JS file

Modularity in programming

Modularity in programming is the breaking up of a large file into independent and interdependent smaller modules, following fixed rules.

The benefits of modularizing your code:

  • Improved code reuse
  • Improved code maintainability
  • It can be loaded on demand
  • etc…

Modular specification

Modularity specifications are the rules that must be followed when modularized code is broken up and combined.

Such as:

  • What syntactic format to use to reference modules (require(‘fs’))
  • What syntax format to use in modules to expose members (not currently learning, learning soon)

The benefits of modular specification: we all abide by the same modular specification to write code, reduce the cost of communication, greatly facilitate the mutual call between each module, self-interest.

We write our own modules and follow the standards of modularity.

CommonJS specification

In the early days, JS did not have modular specifications, JS is becoming more and more popular. If you want to develop large projects with JS, you must have modular specifications, and a large number of JS modular specifications emerged in the civil society.

Modular specification for browser side:

  • AMD specification seajs
  • CMD specifications require. Js

Server side modular specification:

  • CommonJS specification (Node.js follows CommonJS)

In 2015, an official modularity specification was introduced in ES6 with the aim of unifying the modularity specification on the browser side and server side. Modularity of ES6

In the future, vUE and React will use the ES6 modularity specification. ES6’s modular specification Webpack

Node.js follows the CommonJS modularity specification, which specifies the features of modules and how modules depend on each other.

CommonJS provisions:

  1. Within each module, the module variable represents the current module
  2. The module variable is an object whose exports property (module.exports) is the interface to the outside world
  3. Loading a module loads the module.exports property of that module. The require() method is used to load modules.

Classification of Modules in Node.js (★)

In Node.js, modules are divided into three categories according to the different sources of modules:

  • Built-in modules // Built-in modules are officially provided by Node.js, such as fs, PATH, HTTP, etc
  • Custom modules // each created by the user.jsFiles, are custom modules
  • Third-party modules // A module developed by a third party is not an official built-in module or a user-defined module. You need to download the module before using it

Load module

// Load the core module
const fs = require('fs');

// Load the third-party module
const express = require('express');

// Load the custom module
const custom = require('./custom');
Copy the code

Matters needing attention:

  • In addition toglobalNo matter what module we use, rightrequire()Load it before you can use it.
  • To load a custom module, add. /And the suffix can be omitted.js

Implementation of custom modules

Module scope in Node.js

In Node.js, every.js file created by a user is a custom module. Variables, methods, and other members defined in a custom module can only be accessed within the current module. This module-level access restriction is called module scope.

The benefit of module scope is that it avoids global variable contamination

Because a module has a module-level scope, another JS file cannot use the content defined by the current module, as shown in the figure below.

Export import module

In order to properly use the members in the loaded module, CommonJS provides the standard, i.e

  • A module needs to be usedmodule.exportsExport the content to be shared
  • JS files that use modules need to be usedrequire()The import module
  • What does a module export, and what does another JS file that uses a module get

Require () mechanism for loading modules

There are some similarities and differences between the mechanism for loading custom modules and other modules, so I’ll look at it separately.

Load a custom module

  1. The module is cached if the first load is successfulrequire('./a')
  2. The next time you load it from cache, it’s faster
  3. Must be added to load custom modules. /If it is a different path, change it accordingly, otherwise it will be treated as a core module or a third party module
  4. When loading custom modules, if yesrequire('./abc')
    1. Load a file with the same name first. Load a file called ABC
    2. Automatic filling.jsSuffix, and then loadabc.jsfile
    3. Automatic filling.jsonSuffix, and then loadabc.jsonfile
    4. Automatic filling.nodeSuffix, and then loadabc.nodefile
    5. If none of the above files exists, an error is reportedCannot find module './abc'

Load core modules and third-party modules

  1. The module is cached if the first load is successful

  2. The next time you load it from cache, it’s faster

  3. Loading modules must not add./, otherwise it will be considered as a custom module

  4. When loading a module, if require(‘haha’)

    1. Priority is given to loading core modules

    2. To find and load third-party modules, go to module.paths

      [‘E:\tq\ My Item \ Item \shjy73\node\day03\02- code \01-npm\node_modules’, ‘E:\tq\ My Item \shjy73\node\day03\02- code \node_modules’, ‘E:\tq\ My Item \ Shjy73 \node\day03\node_modules’, ‘E:\tq\ My Item \shjy73\node\node_modules’, ‘E:\tq\ My Item \ Shjy73 \node_modules’, ‘E:\tq\ My Item \ Node_modules ‘, ‘E:\tq\ My Item \node_modules’, ‘E:\tq\ My Item \node_modules’, ‘E:\tq\node_modules’, ‘E:\tq\ My Item \node_modules’, ‘E:\tq\node_modules’, ‘E:\node_modules’ ]

    3. Loading a third-party module will look for the node_modules folder from the current directory. If found, go to the node_modules folder to find the corresponding module. If not, go up to node_modules, all the way to the root directory. If not, the module is not found.

Basic Use of Express

Express is a third party module of NodeJS

  • Express website
  • Express Chinese Document

Why express is needed

  • The built-in HTTP module creation server is complicated and inefficient
  • Express encapsulates HTTP modules to greatly improve development efficiency, similar to jquery and DOM
  • With Express, we can quickly and easily develop a Web server and API interface server.

There are many frameworks for NodeJS: Node-HTTP module ==== Express framework ==== koA2 ==== egg.js

Basic procedure for using Express

In the project folder, run NPM I Express to download and install express

Note: Express cannot be installed in a folder named Express or the installation will fail

Steps to build a Web server with Express:

  1. Loading the Express module

  2. Creating an Express Server

  3. Start the server

  4. Listen for browser requests and process them

// Use Express to build the web server
// 1) Load the Express module
const express = require('express');

// 2) Create an Express server
const app = express();

// 3) Start the server
app.listen(3000.() = > console.log('Express server is working now'));

// 4) Listen for the browser request and process it

app.get('GET requested address ', processing function); app.post('POST requested address ', processing function);Copy the code

Res.send () can return data to the browser without worrying about garbled Chinese characters

Express Interface Development (★)

GET an interface

// app.get(' requested URL', callback);
app.get('/api/getbooks'.(req, res) = > {
    // Handle the GET/API/getBooks interface
});

app.get('/'.(req, res) = > {
    // The client does not specify the requested URL, it is handled here.
});

app.get('/v1/get'.(req, res) = > {
  res.setHeader('Access-Control-Allow-Origin'.The '*')
  res.send('Hello.')})Copy the code

App.get (‘*’, (req, res) => {}) it matches all get requests, so put it at the end of all interfaces.

Get the query string

Get the url? Parameter = value & parameter = value

  • The argument part is also called a query string
  • Written request address: http://localhost:3006/test? id=3&bookname=zxx&age=20
  • Obtaining method:req.query
/ / write interface
app.get('/test'.(req, res) = > {
    console.log(req.query); // { id: '3', bookname: 'zxx', age: '20' }
});
Copy the code

Obtaining dynamic parameters

For the url / : id/name / : the age

  • Parameters in this way are called dynamic parameters
  • Written request address: http://localhost:3006/test/3/zs/30
  • The requested URL parameter is mandatory. Otherwise, it cannot match the defined interface
// 1 parameter
// Browser request http://localhost/test/3
// Test the interface to get dynamic parameters
app.get('/test/:id'.(req, res) = > {
	console.log(req.params); {id: 3}
    res.send('Parameters received');
});

// Multiple parameters
http://localhost/test2/3/zhangsan/20 / / the browser's request
// Test the interface to get multiple dynamic parameters
app.get('/test2/:id/:name/:age'.(req, res) = > {
    console.log(req.params); // Get all the dynamic parameters
    // { id: '4', name: 'zhangsan', age: '20' }
    res.send('All received');
});
Copy the code

POST interface

// app.post(' requested URL', callback);
app.post('/api/addbook'.(req, res) = > {
    // Handle POST/API /addbook interface
});

app.post(The '*'.(req, res) = > {
    // Handle all POST requests
})
Copy the code

Gets the body of the POST request

  • GET does not have a request body, but POST does.
  • The request body is the data submitted by the client.

The request body is a query string


app.use(express.urlencoded({extended: false}));

// Any subsequent POST interface can retrieve the contents of the request body via req.body
app.post('/test'.(req, res) = > {
    // Get the request body
    console.log(req.body);
    res.send('Your request body received');
});

Copy the code

Express middleware

Basic introduction

Introduction to Middleware

  • Middleware, specifically the intermediate processing part of a business process.

  • Middleware, the biggest feature of Express, is also the most important design

  • Many third-party modules can be used as middleware for Express, which makes development easier.

  • An Express application is made up of various combinations of middleware

  • Middleware is essentially a function

Middleware Principles

Middleware syntax

  • Middleware is a function
  • There are three basic parameters in the middleware function, req, RES, and next
    • Req is the object associated with the request
    • Res are the response-related objects
    • Next: This is a function that must be called next before the middleware is passed down
  • Grammar:
app.use(function (req, res, next) {
  / /...
  next()
})
Copy the code

Characteristics of Middleware

  • Each middleware function shares reQ objects and res objects
    • In js code, all req objects are one object; All res are one object
  • Don’t callnext(), the program will not be executed backward after the current middleware function is executed
    • Pay attention to the order of the middleware, because it is possible that your middleware functions will not execute because of the order
    • To avoid confusing code logic, don’t write extra code after calling next()
  • A request sent by a client may call multiple middleware in succession for processing
  • useapp.use()Registered middleware, GET and POST requests can be triggered

Express built-in middleware

static

  • What are static resources
    • The CSS file
    • Image files
    • Js file
    • , etc.
  • What are open static resources
    • Open, that is, allow clients to access
  • The specific practices
    • For example, allow clients to access files in the public folder
    • app.use(express.static('public'))

urlencoded

For processing application/ X-www-form-urlencoded requests for data

app.use(express.urlencoded())
Copy the code

json

Middleware for handling content-type application/ JSON

app.use(express.json())
Copy the code

Third-party middleware

Cors (allow cross-domain)

Usage:

  • Download and install CORSnpm i cors
  • const cors = require('cors');— Load the module
  • app.use(cors());— Register middleware

multer

  • Download and install Multer

  • Const multer = require(‘multer’)

  • Const upload = multer({dest: ‘path’});

  • Routing (interface) usage

    const multer = require('multer')
    // const upload = multer({ dest: '路径' })
    const upload = multer({
        dest: path.join(__dirname, '.. /uploads')}); router.post('/add', upload.single('Image name specified by interface documentation'), (req, res) = >Req.body retrieves data of text type req.file retrieves information of file});Copy the code