1. Fs file system module
1.1 What is the FS file system module
Node.js is an official module for manipulating files. It provides the following properties and methods to meet the user’s requirements for manipulating files
- Fs.readfile (), which reads the contents of a specified file
- Fs.writefile (), which is used to write to the specified file
Const fs = require(‘fs’) introduces the fs module
1.2 Reading the contents of a specified file
fs.readFile(path,[options],callback)
Copy the code
- Path: specifies the file path. This parameter is mandatory
- Options: This parameter is optional. What encoding format is used to read the file
- Callback: Mandatory. After the file is read, the result is retrieved through a callback
const fs = require('fs')
fs.readFile('./files/1.txt'.'utf8'.function(err,dataStr) {
// Prints an error result -- err is null if the read succeeds
console.log(err);
// Prints successful results - dataStr is undefined if the data fails to be read
console.log(dataStr);
})
Copy the code
1.3 Writing content to a specified file
fs.writeFile(file,data[options],callback)
Copy the code
- File: Mandatory. A file path must be specified, indicating the file path
- Data: Mandatory, indicating the content to be written
- Options: Optional, which format is used to write file contents. The default format is UTf8
- Callback: Mandatory, the callback function after the file is written
const fs = require('fs')
fs.writeFile('./files/2.txt'.'hello node.js'.function(err) {
// If the file is successfully written, err is null
// If the file fails to be written, err is an error object
console.log(err);
})
Copy the code
1.4 FS module-path Dynamic stitching Problem
When we use the fs module to manipulate files, if the path provided is./ or.. __dirname: indicates the directory in which the current file is located. This command is executed in the directory where the node command is executed
fs.readFile(__dirname + './files/1.txt')
//__dirname is equivalent to completing the complete file storage path: C:\\Users\\50454\\Desktop\\ learning \\ stage 4 front-end and back-end interaction \\2.node
Copy the code
2. Path Path module
The Path module is an official Node module that handles paths
- The path.join() method is used to concatenate multiple path fragments into a complete path string
- The path.basename() method is used to parse the Chinese name from the path string
const path = require(‘path’)
2.1 Path Stitching
The return value is a concatenated path string
const pathStr = path.join(__dirname,'./files/1.txt')
Copy the code
2.2 Obtaining the file name in the Path
const filesName = path.basename(path)
// The return value is the file name in the path
Copy the code
2. The Http module
HTTP is the official module used to create a Web server. You can turn a normal computer into a Web server using the http.createserve () method
const http = require('http')
Copy the code
2.1 Creating a Web Server
- Importing HTTP Modules
- Create a Web server instance
- Bind a request event to a server instance to listen for client requests
- Start the server
// Import the HTTP module
const http = require('http')
// Create web server
const serve = http.createServer()
// Bind the request event
serve.on('request'.(request, res) = > {
console.log('Request successful')})// Start the server
serve.listen(8080.() = > {
console.log('http://127.0.0.1:8080');
})
Copy the code
- Request: A request object that contains client-specific data and attributes
- Response: The response object res.end() responds to the message to the client
2.2 Solve the problem of Chinese garbled characters
Res.end (). Garbled characters appear when sending content to the client. In this case, you need to manually set the content encoding format
res.setHeader('Content-Type'.'text/html; charset=utf-8')
Copy the code
2.3 Respond to different contents based on different URLS
const http = require('http')
const serve = http.createServer()
serve.on('request'.(req, res) = > {
const url = req.url
let content = '<h1>404</h1>'
if(url === '/' || url === '/index') {
content = '< h1 > home page < / h1 >'
} else if(url === '/about') {
content = ' About us
}
res.setHeader('Content-Type'.'text/html; charset=utf-8')
res.end(content)
})
serve.listen(8080.() = > {
console.log('http://127.0.0.1:8080');
})
Copy the code
3. The Node modular
1.1 Classification of modules
- Built-in module
- Custom modules
- Third-party modules
1.2 Module scope
Similar to function scope, variable methods in a custom module that can only be accessed within the current module are called module scope benefits: the problem of preventing global variables from being contaminated
4.npm
4.1 Quickly create pachage.json NPM init-y
4.2 Package Management Configuration File
- Dependencie node: Records which packages NPM Install has installed
- DevDependencies Records the NPM I package name -d
4.3 Loading mechanism of modules
- Loading from cache is preferred
- The built-in modules are loaded with the highest priority
5.express
5.1 Basic use of Experss
Import Express
const express = require('express')
2. Create a Web server
const app = express()
// 4. Listen to client requests and respond to data
app.get('/user'.(req, res) = > {
res.send({name: 'lengran'.age: 18})
})
app.post('/user'.(req, res) = > {
res.send('POST request successful ')})// 3. Call app.listen(port number, successful startup callback) to start the server
app.listen('80'.() = > {
console.log('127.0.0.1');
})
Copy the code
- Get (‘ request URL’,function(req,res) {}) req request object,res response object
- App.post (‘ request URL’,function(req,res) {}) req request object,res response object
- Res.send () : responds to the client with data
5.2 Obtaining Query Parameters carried in the URL
The req.query object is used to access the parameters sent to the server by the client as a query string. Req. query is an empty object by default
5.3 Obtaining Dynamic Parameters in the URL
The URL can be accessed via the req.params object, which is also an empty object by default, by matching dynamic parameters to:
5.4 Hosting Static Resources
Express.static (), if you want more than one managed static resource, call express.static multiple times
app.use(express.static('public))
Copy the code
When accessing a static file, the express.static() function looks for the required files based on the order in which the directories were added
5.5 Hanging the Path prefix
Mount the path prefix before hosting static resource access paths
app.use('/public', express.static('public'))
Copy the code
The /publick prefix must be carried when accessing files in the public directory
5.6 nodemon
If the project code changes, Nodemon will automatically restart the project for us
5.7 express route
Express routes are mappings between client requests and server processing functions. Express routes consist of request type, REQUEST URL address, and processing function
app.method(path, function)
Copy the code
Route Matching process
After each request reaches the server, it must be matched by the route first. After the match is successful, the processing function will be called. If the request type and request URL are matched successfully, the processing function will be executed
Modular routing
- Create the js file corresponding to the routing module
- Call the express.router () function to create the route object
- A specific route is hung on the route object
- Shared routing objects using module.exports
- Use the app.use() function to register the routing module
The app.use() function registers the global middleware to prefix the route app.use(‘/ API ‘, router)
6. The middleware
The middleware for Express, which is essentially a function handler, must contain the next argument
6.1 the next function
The next function is the key to implementing multiple middleware calls in succession, and represents the transfer of the flow relationship to the next middleware or route
6.2 Definition of simplified functions
const mw = (req, res, next) = > {
console.log('The simplest medium piece')
next()
}
Copy the code
6.3 Middleware with global Effect
The middleware that will be triggered by any request from the client when it reaches the server is the globally valid middleware. By calling app.use(middleware function), a globally valid middleware can be defined
const mw = (req, res, next) = > {
console.log('The simplest medium piece')
next()
}
// Global enabler middleware
app.use(mw)
Copy the code
Note: It is possible to register multiple global middleware with multiple app.use()
6.4 Local Middleware
Middleware that does not use the app.use definition is called locally effective middleware
6.5 Classification of Middleware
- Application-level middleware: Middleware bound to an app instance via app.use() or app.get()/app.post()
- Routing level middleware: on express.Router instances
- Error level middleware: Catch errors throughout the project function(Err, REq, RES, Next)
- Express built-in middleware: Express.static (), Express.json, Express.urlencoded
- Third-party middleware: Body-parser Parses request body data
6.6CORS Solves cross-domain Problems
- Run the NPM Install Cors installation
- Use const cors = require(‘cors’)
- Call app.use(cors()) to configure middleware before routing is used
CORS(Cross-domain Resource Sharing) consists of a series of HTTP response headers that determine whether browsers prevent front-end JS code from fetching resources across domains
// CORS response header
Access-Control-Allow-Origin
// Set only http://itcasr.cn requests * to be allowed all
res.serHeader('Access-Control-Allow-Headers'.'http://itcasr.cn')
Access-Control-Allow-Headers
By default, CORS supports only 9 headers sent by the client to the server. If additional headers are sent, you need to declare the additional headers via HEADERS
res.serHeader('Access-Control-Allow-Headers'.'Content-Type'.'X-Custom-Header')
// Allow the client to send content-Type and x-custom-header request headers to the server, separated by commas
Access-Control-Allow-Methods
// By default, CORS supports only GET, POST, and HEAD requests from clients
res.serHeader('Access-Control-Allow-Methods'.'POST, GET, DELETE, HEAD') // Only POST, GET, DELETE, HEAD requests are allowed
res.serHeader('Access-Control-Allow-Methods'.The '*') // All HTTP request methods are allowed
Copy the code
Simple requests and precheck requests are differentCopy the code
2. Simple requests: The client and server request no more than one precheck. 2 No real request is sent until the client and server request succeeds
7 Identity Authentication
Also known as identity authentication, authentication refers to the completion of a certain means to confirm the user identity
Identity authentication in different modes
- Session authentication is recommended for server-side rendering
- JWT authentication is recommended for front – end separation
7.1 Session Authentication Mechanism
Statelessness of HTTP protocol
Each HTTP request from the client is independent. There is no direct relationship between multiple requests. The server does not proactively reserve the status of each HTTP request
Cookie
A string of up to 4KB stored in the user’s browser, consisting of a name, a value, and several other optional attributes that control the validity, security, and scope of the cookie
7.2JWT Authentication Mechanism
Currently the most popular cross-domain authentication solution
7.3JWT components
Header Header payload Payload Signature Signature
7.4 the use of JWT
Js NPM I jsonWebToken express-jwt // jsonWebToken is used to produce JWT strings // Express-jwt is used to parse JWT strings back into JSON objects
Const JWT = require(' jsonWebToken ') const expressJWT = require('express-jwt') const secretKey = 'lengran Jwt. sign({username: 'zs'}, secretKey, {expiresIn: jwt.sign({username: 'zs'}) '30H '}) // Parameter 1: user object information // Parameter 2: encryption key // Parameter 2: configuration object, configurable token expiration time // Restore JWT string to JSON object app.use(expressJWT({secret: secretKey}).unless({path:[/^\/api\//]}))Copy the code
Copy the code