The Node is introduced

Why learn Node.js

  • Enterprise needs
    • Change with server-side development experience
    • front-end
    • back-end
    • Full stack development engineer
    • Basic web development skills
      • The service side
      • The front end
      • Operational deployment
    • Many communities

What is the Node. Js

  • Node.js is a JavaScript runtime
  • In plain English, Node.js is the platform on which JavaScript runs
  • Node.js is neither a language nor a framework, it’s a platform
  • JavaScript in the browser
    • EcmaScript
      • The basic grammar
      • if
      • var
      • function
      • Object
      • Array
    • Bom
    • Dom
  • In the Node. Js JavaScript
    • No Bom, NO Dom
    • EcmaScript
    • This JavaScript execution environment in Node provides some server-level apis for JavaScript
      • For example, reading and writing files
      • Construction of network services
      • Network communication
      • The HTTP server
  • Built with Chrome’s V8 engine on top
    • The code is just a string with a particular format
    • The engine can recognize it, parse it and execute it for you
    • Google Chrome’s V8 engine is currently recognized as the fastest parsing executing JavaScript code
    • The authors of Node.js have ported the V8 engine in Google Chrome and developed a separate JavaScript runtime environment
  • Node.js uses an envent-driven,non-blocking I/O mode that makes it lightweight and efficent.
    • Envent-driven Event driven
    • Non-blocking I/O mode Non-blocking I/O model
    • Ightweight and efficent
  • Node.js package ecosystem,npm,is the larget scosystem of open sourcr libraries in the world
    • NPM is the largest open source ecosystem in the world
    • Most javascript-related packages are stored on NPM to make it easier for developers to download and use
    • npm install jquery

What can Node do

  • Web Server Background
  • Command line tool
    • npm(node)
    • Git (c)
    • Hexo (node)
    • .
  • For front-end engineers, it’s the command line tool that gets the most exposure
    • Their own writing is very little, mainly with others third party
    • webpack
    • gulp
    • npm

start

Installing the Node Environment

  • Check the version of the Node environment
  • Download: nodejs.org/en/
  • Installation:
    • Foolproof installation, all the waynext
    • Once installed, re-installed will upgrade
  • Check whether the Node environment is installed successfully
    • Check the node version number:node --version
    • ornode -v
  • Configuring environment Variables

Parsing executing JavaScript

  1. Create write JavaScript script file
  2. Open the terminal and locate the directory where the script file resides
  3. The inputThe node name of the fileExecute the corresponding file

Note: File names should not be named after Node. js.

File reading and writing

File reading:

// JavaScript in browsers has no file manipulation capabilities
// But JavaScript in Node has file-manipulation capabilities
//fs is short for file-system
// If you want to operate on files in Node, you must refer to the fs core module
// In the fs module, there is an API for all file operations
// For example, fs.readFile is used to read files

// 1. Use fs core module
var fs = require('fs');

// 2. Read files
fs.readFile('./data/a.txt'.function(err,data){
   if(err){
        console.log('File read failed');
   }
    else{
         console.log(data.toString()); }})Copy the code

File write:

// 1. Use fs core module
var fs = require('fs');

// 2. Write data to a file
fs.writeFile('./data/a.txt'.'I am the information written to the file'.function(err,data){
   if(err){
        console.log('File write failed');
   }
    else{
         console.log(data.toString()); }})Copy the code

http

Server:

// 1. Load the HTTP core module
var http = require('http');

Create a Web server using http.createserver ()
var server = http.createServer();

// 3. What the server needs to do
// To provide services: to provide data services
/ / send the request
// Receive the request
// Process the request
// Feedback (send response)
// When the client request comes in, the server automatically triggers the request event, and then executes the second argument: the callback handler
server.on('request'.function(){
    console.log('Received the client's request')})// 4. Bind the port number to start the service
server.listen(3000.function(){
    console.log('runing... ')})Copy the code

Module system in Node

Writing an application using Node is primarily about using:

  • EcmaScript language

    • As with browsers, there is no Bom or Dom in Node
  • The core module

    • Fs for file operations
    • HTTP HTTP for service operations
    • Url path operation module
    • Path Path processing module
    • OS Information about the operating system
  • Third-party modules

    • art-template
    • You must download it through NPM to use it
  • Self-written modules

    • A file created by yourself

What is modularity

  • File scope (modules are independent and must be re-referenced when used in different files)
  • Communication rules
    • Load the require
    • Export exports

CommonJS module specification

Another important concept of JavaScript in Node is the module system.

  • Module scope

  • Use the require method to load the module

  • Use the Exports interface object to export members of the template

    loadingrequire

    Grammar:

    varCustom variable name = require('modules')
    Copy the code

    Function:

    • Executes the code in the loaded module
    • Get the loaded moduleexportsExporting interface Objects

    exportexports

    • Node is module scoped. All members in the default file are valid only for the current module

    • For members that want to be accessible by other modules, we need to mount those exposed members into the Exports interface object

      Export multiple members (must be in an object) :

      exports.a = 123;
      exports.b = function(){
          console.log('bbb')};exports.c = {
          foo:"bar"
      };
      exports.d = 'hello';
      Copy the code

      Export a single member (get a function, string) :

      module.exports = 'hello';
      Copy the code

      The following cases will be covered:

      module.exports = 'hello';
      // The latter will override the former
      module.exports = function add(x,y) {
          return x+y;
      }
      Copy the code

      You can also export multiple members by:

      module.exports = {
          foo = 'hello'.add:function(){
              returnx+y; }};Copy the code

Principle of the module

Exports and a reference to module.exports:

console.log(exports= = =module.exports);	//true

exports.foo = 'bar';

/ / equivalent to the
module.exports.foo = 'bar';
Copy the code

When reassigning exports, exports! = module.exports.

Module. exports returns, no matter what member is in exports.

When to actually use: Export a single member:exports.xxx = xxx; Export multiple members:module.exports or modeule. Exports = {};Copy the code

conclusion

// Reference the service
var http = require('http');
var fs = require('fs');
// Reference the template
var template = require('art-template');
// Create a service
var server = http.createServer();
// Public path
var wwwDir = 'D:/app/www';
server.on('request'.function (req, res) {
    var url = req.url;
    // Read the file
    fs.readFile('./template-apche.html'.function (err, data) {
        if (err) {
            return res.end('404 Not Found');
        }
        fs.readdir(wwwDir, function (err, files) {
            if (err) {
                return res.end('Can not find www Dir.')}// Use the template engine to parse and replace the template string in data
            // Go to xmptempletelist.html to write template syntax
            var htmlStr = template.render(data.toString(), { 
                title: 'D:/app/ WWW/'.files:files 
            });
            // Send response datares.end(htmlStr); })})}); server.listen(3000.function () {
    console.log('running.... ');
})
Copy the code
1.Each in jQuery is provided by es5 (not compatible with IE8). Each in jQuery is provided by a third-party jQuery library (if needed)2The following version is1.JQuery forEach (forEach); jQuery forEach (forEach); jQuery forEach (forEach) If you want to use it, you must convert it to an array ([].slice.call(jQuery instance object))2.The module exports multiple members and a single member3.301and302The difference between:301Permanent redirection, the browser will remember302Temporary redirection4.exportsandmoduleExports: there is one in every modulemoduleobjectmoduleObject has oneexportsObject to which we can mount all the members we need to exportmoduleExports interface objects`module.exports.xxx = xxx`But writing too much at a time can be troublesome, so Node provides a member for each module to simplify the code`exports`
    `exports === module.exports`The results fortrueSo it's totally ok`exports.xxx = xxx`Must be used when a module needs to export individual members`module.exports = xxx`Method, =, is used`exports = xxx`It doesn't work because each module ends upreturnismoduleExports, andexportsjustmoduleA reference to.exports, so`exports`It doesn't matter if you reassign`module.exports`. There is a special assignment:`exports = module.exports`This is used to create a new reference relationship.Copy the code

Require’s loading rules

  • The core module

    • Module name
  • Third-party modules

    • Module name
  • The user wrote it

    • The path

Require loading rules:

  • Preferentially load from cache

  • Determine the module identifier

    • The core module
    • Self-written modules (path-based modules)
    • Third-party modules (node_modules)
      • The identity of the third party module is the name of the third party module (no third party module can have the same name as the core module)
      • npm
        • Developers can publish written framework libraries to NPM
        • The user downloads it by using the NPM command
      • Usage:Var name = require(' NPM install ')
        • node_modules/express/package.json main
        • If package.json or main does not hold, look for the selected item: index.js
        • If none of the preceding conditions is met, go to node_modules in the directory of the previous level and search for the file according to the preceding rules until the root directory of the current file cannot be found. Finally, an error message is reported
// If not path identifier
// Path identifier:
    // The current directory cannot be omitted
    / /.. / The upper directory cannot be omitted
    // / XXX = D:/ XXX
    // Almost no use with absolute paths (D:/a/foo.js)
// The first digit represents the root directory of the disk where the current file module resides
// require('./a'); 


// Core module
// The core module is essentially a file, the core module file has been compiled into the binary file, we just need to load the name of the file
require('fs'); 

// Third party module
// All third party modules must be downloaded via NPM (NPM I node_modules), and can be used by requiring (' package name ')
// The third party package name cannot be the same as the core module name
// It is neither a core module nor a path module
// Find node_modules for the current directory
// Then go to node_modules/art-template
// node_modules/art-template/package.json
// node_modules/art-template/package.json main property
// The main attribute records the entry module of the art-template
// Then load and use this third-party package
// The file is actually loaded

// If package.json does not exist or the entry module specified by mian does not exist
// Node will automatically find index.js in the directory
If main is not specified, the index.js file will be loaded
//      
        // If the conditions are not met, the system searches for the directory at the upper level
// Note: a project has only one node_modules, which is placed in the project root directory. Subdirectories can directly call files in the root directory
var template = require('art-template');

Copy the code

In the module identifier/And file operation path/

File operation path:

// All file manipulation apis we use are asynchronous
// Just like ajax requests
// Read the file
// Corresponds to the root directory of the disk where the current module resides
//./index.txt Relative to the current directory
TXT relative to the current directory
TXT Absolute path, the root directory of the current file module
// d:express/index. TXT Absolute path
fs.readFile('./index.txt'.function(err,data){
    if(err){
       return  console.log('Read failed');
    }
    console.log(data.toString());
})
Copy the code

Module operation path:

// In module loading, the relative path./ cannot be omitted
// this is omitted. Also the root directory of the disk
require('./index') ('hello')
Copy the code

npm

  • Node Package Manage node Package Manage
  • NPM install –save jQuery: NPM install –save jQuery: NPM install –save jQuery

NPM web site

Npmjs.com is used to search for NPM packages

NPM command line tool

NPM is a command-line tool that is installed as soon as Node is installed.

NPM also has a version concept. You can view the version of NPM by using NPM –version

Upgrade NPM (upgrade yourself) :

npm install --global npm
Copy the code

Common commands

  • NPM init(generate package.json specification file)
    • NPM init -y(can skip the wizard and quickly generate)
  • npm install
    • Install all the dependencies in the Dependencies option at once
    • Abbreviation (NPM I)
  • NPM install package name
    • Only download
    • Short (NPM I package name)
  • NPM install –save package name
    • Download and save dependencies (dependencies option in package.json file)
    • Short (NPM I package name)
  • NPM uninstall the package name
    • Delete only, if there are dependencies will still be saved
    • Short (NPM UN package name)
  • NPM uninstall –save package name
    • Deleting the dependency information will also be deleted
    • Short (NPM UN package name)
  • npm help
    • View user Help
  • NPM — help command
    • See help for specific commands (NPM uninstall –help)

Resolve NPM wall issues

NPM stores package files on a server in a foreign country, which is sometimes walled and slow, so we need to solve this problem.

Developer.aliyun.com/mirror/NPM?…

Install taobao CNPM:

npm install -g cnpm --registry=https://registry.npm.taobao.org;
Copy the code
#It can be executed in any directory
#--global indicates global installation, not current directory
#--global can't be omitted, otherwise it won't work
npm install --global cnpm
Copy the code

Replace the previous NPM with CNPM when installing the package.

#It is slow to download jQuery package from NPM server abroad
npm install jQuery;

#Using CNPM, you will download jQuery through Taobao's server
cnpm install jQuery;
Copy the code

If you do not want to install CNPM and want to use Taobao’s server to download:

npm install jquery --registry=https://npm.taobao.org;
Copy the code

But adding parameters manually each time is troublesome, so we can add this option to the configuration file:

npm config set registry https://npm.taobao.org;

#View NPM configuration information
npm config list;
Copy the code

As long as you go through the above configuration command, all NPM install will be downloaded through Taobao’s server

package.json

Each project should have a package.json file (package description file, like product specification)

This file can be automatically initialized by NPM init


DNPM init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See`npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency inthe package.json file. Press ^C at any time to quit. package name: Sorry, name can only contain urL-friendly characters. Package name: CLSversion: (1.0. 0)
descriptionEntry point: (main.js) Test Command: Git Repository: Keywords: author: xiaochenlicense: (ISC) About to write to D: code\node module system \package.json: {"name": "cls"."version": "1.0.0"."description": "This is a test project."."main": "main.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "xiaochen"."license": "ISC"
}


Is this OK? (yes) yes
Copy the code

The most useful option for now is the Dependencies option, which helps us save dependencies for third-party packages.

Don’t worry if node_modules is deleted. NPM install automatically downloads dependencies from package.json in the control panel.

  • It is recommended to have one in the root directory of each projectpackage.jsonfile
  • Suggest to performNPM install package nameAll the time--saveOption, which is used to save dependency information

Package. The json and package – lock. Json

Package-lock. json file will not be available in NPM 5

Npm5 was added to this file later

When you install a package, NPM generates or updates the package-lock.json file

  • Do not install nPM5 or later--saveParameter, which automatically saves dependency information
  • Packages are created or updated automatically when you install thempackage-lock.jsonfile
  • package-lock.jsonThis file will containnode_modulesInformation about all packages in the
    • In this case re-npm installWhen the speed can be increased
  • According to the file, there is onelockCall it the lock
    • thislockUsed to lock the version
    • If the project depends on1.1.1version
    • If you re-install, you will actually download the smallest version instead of1.1.1
    • package-lock.jsonAnother function is to lock the version number to prevent automatic upgrades

Path Path operation module

Reference documents: nodejs.org/docs/latest…

  • Path. basename: Specifies the name of the file to obtain the path, including the extension by default
  • Path. dirname: Gets the directory part of the path
  • Path. extName: Gets the extension part of a path
  • Path. parse: Converts paths to objects
    • Root: indicates the root path
    • Directory dir:
    • Base: indicates the file name with the suffix
    • Ext: suffix
    • Name: indicates the file name without the suffix
  • Path. join: indicates the joining path
  • Path. IsAbsolute: Check whether A path is an absolute path [External link picture transfer failure, the source station may have anti-theft mechanism, you are advised to save the picture directly upload (IMg-hxze4STW-1584422065205)(C:\Users\A\AppData\ Typora\ Typora-use) r-images\image-20200315150610001.png)]

Other members of Node (__dirname,__filename)

In addition to the require,exports, and other module related apis, there are two special members in each module:

  • __dirname is a member that can be used to dynamically retrieve the absolute path to the directory that the current file module belongs to

  • __filename, which can be used to dynamically get the absolute path of the current file (including the filename)

  • __dirname and filename are not affected by the path where the node command is executed

    [img-vzWungQQ-1584422065205] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [img-vzWungQQ-1584422065205] (C:\Users\A\AppData\ Typora-user-images \imag e-20200315151551873.png)]

Using relative paths is unreliable in file operations, because the path of file operations in Node is designed to be relative to the path where the Node command is executed.

So to solve this problem, just change the relative path to the absolute path (the absolute path is not affected at all).

We can use __dirname or __filename to help us solve this problem

It is recommended to use path.join() to assist in the concatenation of paths, in order to avoid some low-level errors associated with manual concatenation

var fs = require('fs');
var path = require('path');

// console.log(__dirname + 'a.txt');
The path.join method converts all relative paths in file operations to dynamic absolute paths
fs.readFile(path.join(__dirname + '/a.txt'),'utf8'.function(err,data){
	if(err){
		throw err
	}
	console.log(data);
});
Copy the code

Add: The path identifier in the module is not affected by the path here (i.e. relative to the file module).

Note:

The path identifier in the module is inconsistent with the relative path identifier in the file operation

The path identifier in a module is not affected by the path of the node command relative to the current file module

Express (fast)

Author: Tj

In some ways, native HTTP was inadequate to meet our development needs, so we needed to use a framework to speed up our development. The purpose of a framework is to improve efficiency and make our code highly uniform.

There are many Web development frameworks in Node. Learning Express

  • http://expressjs.com/, where the main encapsulation is HTTP.

  • / / 1 installation
    / / 2 package
    var express = require('express');
    // 3 Create the server application
    // Http.createserver ();
    var app = express();
    
    // Expose the specified directory
    // Once this is done, all resources in the public directory can be accessed through /public/xx
    // Open resources in Express is an API
    app.use('/public/',express.static('/public/'));
    
    // The template engine opens templates in Express as an API
    
    // When the server receives a get request /, the callback handler is executed
    app.get('/'.function(req,res){
        res.send('hello express');
    })
    
    // the same as server.listen
    app.listen(3000.function(){
        console.log('app is runing at port 3000');
    })
    Copy the code

Learning to Express

start

Installation: [Img-jTZxTWPE-1584422065206] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-jTZxTWPE-1584422065206] (C:\Users\A\AppData\Roaming\ typora-user-images\imag e-20200310123723079.png)]
cnpm install express
Copy the code
hello World :[Img-eipqsron-1584422065207] (C:\Users\A\AppData\ Typora\ typora-user-Image) [Img-eipqSRon-1584422065207] (C:\Users\A\AppData\ Typora\ Typora-user-image s\image-20200310124850557.png)]
/ / into the express
var express = require('express');

// create app
var app = express();

//  2. 
app.get('/'.function(req,res){
    / / 1
    // res.write('Hello');
    // res.write('World');
    // res.end()

    / / 2
    // res.end('hello world');

    / / 3
    res.send('hello world');
})

app.listen(3000.function(){
    console.log('express app is runing... ');
})
Copy the code
The basic routing

Routing:

  • Request method

  • Request path

  • Request handler function

get:

// When you request/with the get method, execute the corresponding handler
app.get('/'.function(req,res){
    res.send('hello world');
})
Copy the code

post:

// When you request/with the post method, execute the corresponding handler
app.post('/'.function(req,res){
    res.send('hello world');
})
Copy the code
Express static service API
// App. use is not just for handling static resources, it can do a lot of things (body-parser configuration)
app.use(express.static('public'));

app.use(express.static('files'));

app.use('/stataic',express.static('public'));
Copy the code
/ / into the express
var express = require('express');

/ / create the app
var app = express();

// Open static resources
// 1. When the file starts with /public/, go to the./public/ directory to find the corresponding resource
/ / visit: http://127.0.0.1:3000/public/login.html
app.use('/public/',express.static('./public/')); 

// 2. If the first parameter is omitted, it can be accessed by omitting /public
/ / visit: http://127.0.0.1:3000/login.html
// app.use(express.static('./public/'));   

/ / 3. Visit: http://127.0.0.1:3000/a/login.html
// a is the alias of public
// app.use('/a/',express.static('./public/')); 

//  
app.get('/'.function(req,res){
    res.end('hello world');
});

app.listen(3000.function(){
    console.log('express app is runing... ');
});
Copy the code
Used in Expressart-templeteA template engine
  • Art-template official document
  • There are many third-party template engines available in Node, not just oneart-template
    • Also EJS, Jade (PUg), Handlebars, Nunjucks

Installation:

NPM install --save art-template NPM install --save express-art-template express-art-templateCopy the code

Configuration:

app.engine('html'.require('express-art-template'));
Copy the code

Use:

app.get('/'.function(req,res){
    // Express by default goes to the views directory to find index.html
    res.render('index.html', {title:'hello world'     
    });
})
Copy the code

If you want to change the default views render store directory, you can:

// Do not write the first parameter views wrong
app.set('views', directory path);Copy the code
Get form request data in Express
Get request data:

Express has a built-in API to retrieve data directly from req.query

// Get the data entered by the user using the requery method
// req.query returns only the data of the GET request
 var comment = req.query;
Copy the code
Get POST request data:

There is no built-in API for retrieving the form POST request body in Express, so we need to use a third-party package body-Parser to retrieve the data.

Installation:

npm install --save body-parser;
Copy the code

Configuration:

// Configure the parse form POST request body plug-in (note: must be before app.use(router))

var express = require('express')
/ / package
var bodyParser = require('body-parser')

var app = express()

/ / configuration of the body - parser
// Once this configuration is added, there will be an additional property on the REQ request object: body
// This means that you can get the form POST request data directly from req.body
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
Copy the code

Use:

app.use(function (req, res) {
  res.setHeader('Content-Type'.'text/plain')
  res.write('you posted:\n')
  // Form request data can be obtained via req.body
  res.end(JSON.stringify(req.body, null.2))})Copy the code

Used in Expressexpress-sessionPlug-in operation

Reference documents: github.com/expressjs/s…

Installation:

npm install express-session
Copy the code

Configuration:

// The plugin adds a member to the REQ request object :req.session is an object by default
// This is the simplest configuration
//Session is implemented based on cookies
app.use(session({
  // Configure encryption string, it will be on the original basis and string concatenation to encrypt
  // The purpose is to increase security and prevent malicious forgery by clients
  secret: 'keyboard cat'.resave: false.saveUninitialized: true.// Assigns a key directly by default, regardless of whether Session is applicable
  cookie: { secure: true}}))Copy the code

Use:

/ / read
// Add Session data
// Session is an object
req.session.foo = 'bar';

/ / write
// Get session data
req.session.foo

/ / delete
req.session.foo = null;
delete req.session.foo
Copy the code

Tip:

By default, Session data is stored in the system. Once the server restarts, a real production environment stores sessions persistently.

Implement ADUS projects with Express

Modularity idea

How modules are divided:

  • Module responsibilities should be single

Javascript modularity:

  • The Node of the CommonJS
  • In the browser:
    • AMD require.js
    • CMD sea.js
  • Official support has been added in ES6

start

  • Initialize the
  • Template processing

Routing design

Request method Request path The get parameter Post parameters note
GET /students Rendering the home page
GET /students/new Render to add student page
POST /students/new name,age,gender,hobbies Process add student request
GET /students/edit id Render edit page
POST /students/edit id,name,age,gender,hobbies Handling edit requests
GET /students/delete id Handling delete requests

Extract routing module

router.js:

/** * Router.js Routing module * responsibilities: * handle routing * set specific request functions according to different request methods + request path * Module responsibilities should be single, we divide modules to enhance code maintainability, improve development efficiency */
var fs = require('fs');

// Express specializes in a better way
// It is used to provide routing
var express = require('express');
// 1 Create a routing container
var router = express.Router();
// 2 Mount the routes to the routing container

router.get('/students'.function(req, res) {
    // res.send('hello world');
    // The second argument to readFile is optional. Passing utF8 to readFile tells it to encode the file as utF8 and convert it to the character we know
    // You can also use data.tostring ()
    fs.readFile('./db.json'.'utf8'.function(err, data) {
        if (err) {
            return res.status(500).send('Server error.')}// The file data read is string data
        // console.log(data);
        // The data read from the file must be strings, so be sure to manually convert to objects
        var students = JSON.parse(data).students;
        res.render('index.html', {
            // Read file data
            students:students
        })
    })
});

router.get('/students/new'.function(req,res){
    res.render('new.html')}); router.get('/students/edit'.function(req,res){}); router.post('/students/edit'.function(req,res){}); router.get('/students/delete'.function(req,res){});// 3 Export the router
module.exports = router;

Copy the code

app.js:

var router = require('./router');

// router(app);
// Mount the routing container to the app service
// Mount the route
app.use(router);
Copy the code

Design API file modules for manipulating data

Find and findIndex in ES6:

Find takes a method as an argument and returns a condition inside the method

Find will facilitate all elements, executing the function you’ve given with a conditional return value

The element that matches this condition is returned as the value of the find method

If there is no element that matches this condition at the end of the loop, Return undefined[external chain picture transfer failed, the source station may have anti-theft mechanism, it is recommended to save the picture directly upload (IMg-b2bD4zDw-1584422065207)(C:\Users\A\AppData\ Typora\typora-user) -images\image-20200313103810731.png)]

/** ** student.js */ ** student.js */
var fs = require('fs');
 /** * get all students * return [] */
exports.find = function(){}/** * get add save student */
exports.save = function(){}/** * Update student */
exports.update = function(){}/** * delete student */
exports.delete = function(){}Copy the code

steps

  • The process template

  • Configure static open resources

  • Configuring the Template Engine

  • Simple routing, /studens render static pages out

  • Routing design

  • Extract routing module

  • Since the next series of business operations need to process file data, we need to wrap student.js’.

  • Write the student.js file structure first

    • Query API for all student columns
    • findById
    • save
    • updateById
    • deleteById
  • Implement specific functions

    • The request was received through the route. Procedure
    • Accept parameters in the request (GET, POST)
      • req.query
      • req.body
    • Call the data manipulation API to process the data
    • Send a request to the client based on the operation result
  • Sequence of business functions

    • The list of
    • add
    • The editor
    • delete

Inheritance of subtemplates and templates (template engine advanced syntax)

Note:

Page template:

<! DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <meta http-equiv=" x-UA-compatible "content="ie=edge"> href="/node_modules/bootstrap/dist/css/bootstrap.css"/> {{ block 'head' }}{{ /block }} </head> <body> <! - through the include import part of public - > {{include '. / header. HTML '}} <! - leave a location Let other content to fill - > {{block 'content'}} < h1 > the default content < / h1 > {{/ block}} <! - through the include import part of public - > {{include '. / footer. HTML '}} <! - public style -- -- > < script SRC = "/ node_modules/jquery/dist/jquery js" > < / script > < script src="/node_modules/bootstrap/dist/js/bootstrap.js" ></script> {{ block 'script' }}{{ /block }} </body> </html>Copy the code

Template inheritance:

The header page:

<div id="">
	<h1>Public head</h1>
</div>
Copy the code

Footer page:

<div id="">
	<h1>Common bottom</h1>
</div>
Copy the code

Use of template page:

<! -- Extends the template also layout.html --> <! Add the contents of layout.html as the contents of index. HTML --> {{extend'./layout.html'}} <! Fill the template page with new data --> <! This replaces the data in the Layout page content --> <! -- style --> {{block'head' }}
	<style type="text/css">
		body{
			background-color: skyblue;
		}
	</style>
{{ /block }}
{{ block 'content' }}
	<div id="">
		<h1>Index page content</h1></div> {{ /block }} <! -- the contents of the js section --> {{block'script' }}
	<script type="text/javascript">
		
	</script>
{{ /block }}
Copy the code

Final display:

[Img-3RI3LO3O-1584422065208] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-3RI3LO3O-1584422065208] (C:\Users\A\AppData\Roaming\ typora-user-images\imag e-20200316134759517.png)]

MongoDB

Relational and non-relational databases

Relational databases (tables are relationships, or relationships between tables).

  • All relational databases need to passsqlLanguage to operate
  • All relational databases need to design the table structure before operation
  • And data tables support constraints
    • The only
    • A primary key
    • The default value
    • Is not empty

Non-relational databases

  • Non-relational databases are very flexible
  • Some relational databases are key-value pairs
  • But MongDB is the non-relational database that looks most like a relational database
    • Database – database
    • Data table – collection (Array)
    • Table record – document object

You can have multiple databases in a database, multiple collections (arrays) in a database, and multiple documents (table records) in a collection

{
    qq: {user: [{}, {}, {}. }}Copy the code
  • That means you can store data in there as much as you want. There’s no structure

The installation

  • download

    • Download: www.mongodb.com/download-ce…
  • The installation

    npm i mongoose
    Copy the code
  • Configuring environment Variables

  • Finally, type mongod –version to test whether the installation is successful

Start and close the database

Activation:

#By default, mongodb uses /data/db in the complex root directory where the mongod command is executed as its data storage directory
#Therefore, manually create /data/db before running this command for the first time
mongod
Copy the code

If you want to change the default data store directory, you can:

Mongod --dbpath = Data store directory pathCopy the code

Stop:

On the console where services are started, Ctrl+C; Or close the console where the service is started.Copy the code

[Img-b0mFRDAa-1584422065208] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-b0MfrDAa-1584422065208] (C:\Users\A\AppData\Roaming\ typora-user-images\imag e-20200314101047100.png)]

Connecting to a Database

Connection:

By default, this command connects to the native MongoDB service mongoCopy the code

Exit:

Enter exit to exit the connectionCopy the code

[ImG-j7zka0Gs-1584422065209] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-J7zka0Gs-1584422065209] [imG-J7Zka0Gs-1584422065209 e-20200314100821112.png)]

Basic commands

  • show dbs
    • View the database list (all databases in the database)
  • db
    • View the currently connected database
  • Use Database name
    • Switch to the specified database, (if not new)
  • show collections
    • View all tables in the current directory
  • The name of the table. The find ()
    • View the details in the table

How do I operate the MongoDB database in Node

Use officialMongoDBPackage to operate

Mongo. Making. IO/node – mongod…

Using third-party packagesmongooseTo manipulate the MongoDB database

Third-party package: Mongoose Based on the official MongoDB package to make a package again, named Mongoose, is developed by the WordPress project team.

​ mongoosejs.com/

[Img-wtyrSv2B-1584422065209] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-wTYRSv2B-1584422065209] (C:\Users\A\AppData\Roaming\ typora-user-images\imag e-20200314105632745.png)]

[imG-CCDS8NDM-1584422065210] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-CCDS8NDM-1584422065210] (C:\Users\A\AppData\Roaming\ typora-user-images\imag e-20200314105717993.png)]

Study Guide (Steps)

Official document learning: mongoosejs.com/docs/index….

Designing Scheme publish Models (creating tables)

/ / 1. The package
// Note: only after this can require use
var mongoose = require('mongoose');

// Get the schema
var Schema = mongoose.Schema;

2. Connect to the database
// Specify that the database does not need to exist after you connect to it, the database will be created automatically after you insert the first database
mongoose.connect('mongodb://localhost/test');

// 3.
/ / the user table
var userSchema = new Schema({
	username: { / / name
		type: String.require: true // Add constraints to ensure data integrity
	},
	password: {
		type: String.require: true
	},
	email: {
		type: String}});// 4. Publish the document structure as model
// The mongoose. Model method is used to publish an architecture as a model
// First argument: Pass in an uppercase singular string to indicate the name of your database
// Mongoose will automatically generate the string of uppercase nouns into the set name of lowercase plural nouns
// For example, this will become the users collection name
// The second argument: architecture
// Return value: model constructor
var User = mongoose.model('User', userSchema);
Copy the code

Add Data (add)

// 5. Use the model constructor to manipulate the data in User
var user = new User({
	username: 'admin'.password: '123456'.email: '[email protected]'
});

user.save(function(err, ret) {
	if (err) {
		console.log('Save failed');
	} else {
		console.log('Saved successfully');
		console.log(ret); }});Copy the code

Delete (delete)

Delete all based on conditions:

User.remove({
	username: 'xiaoxiao'
}, function(err, ret) {
	if (err) {
		console.log('Delete failed');
	} else {
		console.log('Deleted successfully');
		console.log(ret); }});Copy the code

Delete one according to the condition:

Model.findOneAndRemove(conditions,[options],[callback]);
Copy the code

Delete one by id:

User.findByIdAndRemove(id,[options],[callback]);
Copy the code

Update (change)

Update all:

User.remove(conditions,doc,[options],[callback]);
Copy the code

Update one based on the specified condition:

User.FindOneAndUpdate([conditions],[update],[options],[callback]);
Copy the code

Update one based on id:

// Update table data by id
User.findByIdAndUpdate('5e6c5264fada77438c45dfcd', {
	username: 'junjun'
}, function(err, ret) {
	if (err) {
		console.log('Update failed');
	} else {
		console.log('Update successful'); }});Copy the code

Query (search)

Query all:

// Query all
User.find(function(err,ret){
	if(err){
		console.log('Query failed');
	}else{
		console.log(ret); }});Copy the code

Conditional query all:

// Query by condition
User.find({ username:'xiaoxiao' },function(err,ret){
	if(err){
		console.log('Query failed');
	}else{
		console.log(ret); }});Copy the code

Conditional query single:

// Query a single object ({})
// Query the first data in the table using findOne method
User.findOne({
	username: 'xiaoxiao'
}, function(err, ret) {
	if (err) {
		console.log('Query failed');
	} else {
		console.log(ret); }});Copy the code

Use Node to operate the MySQL database

Documents: www.npmjs.com/package/mys…

Installation:

npm install --save  mysql
Copy the code
// Import mysql package
var mysql      = require('mysql');

// Create a connection
var connection = mysql.createConnection({
  host     : 'localhost'./ / native
  user     : 'me'./ / account root
  password : 'secret'./ / password 12345
  database : 'my_db'	// Database name
});
 
// Connect to database (open refrigerator door)
connection.connect();
 
// Perform data operation (put elephant in refrigerator)
connection.query('SELECT * FROM `users` '.function (error, results, fields) {
  if (error) throw error;// Throw an exception to prevent the code from executing further
  // No abnormal output is printed
  console.log('The solution is: ',results);
});

// Close connection (close refrigerator door)
connection.end();
Copy the code

Asynchronous programming

The callback function

In case of failure:

function add(x,y){
    console.log(1);
    setTimeout(function(){
        console.log(2);
        var ret = x + y;
        return ret;
    },1000);
    console.log(3);
    // The timer will not wait until the previous one, so the default value is undefined
}

console.log(add(2.2));
// result is 1, 3, undefined 4
Copy the code

[img-kvt0jpFF-1584422065210] [C:\Users\A\AppData\ Typora\ Typora-user-images \imag] [img-kvt0jpFF-1584422065210] [C:\Users\A\AppData\Roaming\ typora-user-images\imag e-20200313085008929.png)]

Use the callback function to solve:

Callback function: Retrieves operations inside a function. (Get the output from the input)

var ret;
function add(x,y,callback){
    // Callback is the callback function
    // var x = 10;
    // var y = 20;
    // var callback = function(ret){console.log(ret); }
    console.log(1);
    setTimeout(function(){
        var ret = x + y;
        callback(ret);
    },1000);
    console.log(3);
}
add(10.20.function(ret){
    console.log(ret);
});
Copy the code

Note:

Anyone who needs to be a function within the results of the asynchronous operation (setTimeout, readFile writeFile, ajax, readdir)

This must be done via a callback (asynchronous apis always have a callback)

ajax:

Encapsulate get methods based on native XMLHttpRequest:

var oReq = new XMLHttpRequest();
// The specified function is called when the request is successfully loaded
oReq.onload = function(){
    console.log(oReq.responseText);
}
oReq.open("GET"."Request path".true);
oReq.send();
Copy the code
function get(url,callback){
    var oReq = new XMLHttpRequest();
    // The specified function is called when the request is successfully loaded
    oReq.onload = function(){
        //console.log(oReq.responseText);
        callback(oReq.responseText);
    }
    oReq.open("GET", url,true);
    oReq.send();
}
get('data.json'.function(data){
    console.log(data);
});
Copy the code

Promise

Callback hell:

(C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [img- rxo9gjqK-1584422065211] [img- rxo9gjqK-1584422065211] [img- rxo9GjqK-1584422065211] [img- rxo9GjqK-1584422065211] [img- rxo9GjqK-1584422065211 e-20200314143410972.png)]

File read cannot determine the order of execution (file execution order is determined by file size) (asynchronous API cannot guarantee file execution order)

var fs = require('fs');

fs.readFile('./data/a.text'.'utf8'.function(err,data){
	if(err){
		// 1 read failure Print output read failure
		return console.log('Read failed');
		// 2 Throws an exception
		// Block program execution
		// Print the error message to the console
		throw err;
	}
	console.log(data);
});

fs.readFile('./data/b.text'.'utf8'.function(err,data){
	if(err){
		// 1 read failure Print output read failure
		return console.log('Read failed');
		// 2 Throws an exception
		// Block program execution
		// Print the error message to the console
		throw err;
	}
	console.log(data);
});
Copy the code

Order is guaranteed by nesting callbacks:

var fs = require('fs');

fs.readFile('./data/a.text'.'utf8'.function(err,data){
	if(err){
		// 1 read failure Print output read failure
		return console.log('Read failed');
		// 2 Throws an exception
		// Block program execution
		// Print the error message to the console
		throw err;
	}
	console.log(data);
	fs.readFile('./data/b.text'.'utf8'.function(err,data){
		if(err){
			// 1 read failure Print output read failure
			return console.log('Read failed');
			// 2 Throws an exception
			// Block program execution
			// Print the error message to the console
			throw err;
		}
		console.log(data);
		fs.readFile('./data/a.text'.'utf8'.function(err,data){
			if(err){
				// 1 read failure Print output read failure
				return console.log('Read failed');
				// 2 Throws an exception
				// Block program execution
				// Print the error message to the console
				throw err;
			}
			console.log(data);
		});
	});
});
Copy the code

[ImG-5OXT6AIS -1584422065211] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-5OXT6AIS -1584422065211] (C:\Users\A\AppData\Roaming\ typora-user-images\imag E-20200314144807008.png)] EcmaScript6 adds an API:Promise to solve the problem. [ImG-06ZCCJTX-1584422065211] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-06ZCCJTX-1584422065211] (C:\Users\A\AppData\ Typora-user-images \ Imag e-20200314150050839.png)]

  • -Serena: I Promise
  • Promises aren’t asynchronous per se, but they tend to encapsulate an asynchronous task internally

Basic syntax:

// An API Promise has been added to EcmaScript 6
// Promise is a constructor

var fs = require('fs');
// 1 Create the Promise container resolve: resolve, reject: fail
var p1 = new Promise(function(resolve, reject) {
	fs.readFile('./a.text'.'utf8'.function(err, data) {
		if (err) {
			// console.log(err);
			// Change the Pending state of the container to Rejected
			reject(err);
		} else {
			// console.log(data);
			// Change the container's Pending state to resolve
			resolve(1234); }}); });// When p1 succeeds, then the specified operation is performed
The function received by the then method is the resolve function in the container
p1
	.then(function(data) {
		console.log(data);
	}, function(err) {
		console.log('File reading failed', err);
	});

Copy the code

[img-04QA4y60-1584422065212] [C:\Users\A\AppData\ Typora\ Typora-user-images \imag] [img- 04QA4y60-1584422065212] [img- 04QA4y60-1584422065212] [img- 04QA4y60-1584422065212] [img- 04QA4y60-1584422065212 e-20200315100611620.png)]

Chain cycle: [Img-erguuv5J-1584422065212] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [Img-erguuv5J-1584422065212] [IMG-erguuv5J-1584422065212] [IMG-erguuv5J-1584422065212] (C:\Users\A\AppData\ Typora-user-images \imag e-20200315125559136.png)]

ReadFile encapsulates the Promise:

var fs = require('fs');

function pReadFile(filePath) {
	return new Promise(function(resolve, reject) {
		fs.readFile(filePath, 'utf8'.function(err, data) {
			if (err) {
				reject(err);
			} else{ resolve(data); }}); }); } pReadFile('./a.txt')
	.then(function(data) {
		console.log(data);
		return pReadFile('./b.txt');
	})
	.then(function(data) {
		console.log(data);
		return pReadFile('./a.txt');
	})
	.then(function(data) {
		console.log(data);
	})

Copy the code

All of Mongoose’s apis support Promise:

// Query all
User.find()
	.then(function(data){
        console.log(data)
    })
Copy the code

Registration:

User.findOne({username:'admin'},function(user){
    if(user){
        console.log('User already exists')}else {
        new User({
             username:'aaa'.password:'123'.email:'fffff'
        }).save(function(){
            console.log('Registration successful'); })}})Copy the code
User.findOne({
    username:'admin'
})
    .then(function(user){
        if(user){
            // The user already exists and cannot be registered
            console.log('User already exists');
        }
        else{
            // The user does not exist
            return new User({
                username:'aaa'.password:'123'.email:'fffff'
            }).save();
        }
    })
    .then(funciton(ret){
		console.log('Registration successful');
    })
Copy the code

Generator

Async function

other

Automatically restart after modifying the code

We can use a third-party naming line tool here: Nodemon to help us solve the problem of frequently modifying code to restart the server.

Nodemon is a third-party command line tool developed based on Node.js, which needs to be installed independently when we use it:

This command can be executed in any directoryglobalNPM install -- can be executed in any directory for installed packagesglobalNodemon NPM install -g nodemon # If the installation fails, you can use CNPM to install CNPM install -g nodemonCopy the code

Use after installation:

# use nodemon nodemon app.jsCopy the code

As long as the service is started by Nodemon, it will monitor your file changes and automatically restart the server for you when the file changes.

Encapsulating asynchronous APIS

Callback function: gets the result of an asynchronous operation

function fn(callback){
    // var callback = funtion(data){ console.log(data); }
	setTimeout(function(){
        var data = 'hello';
        callback(data);
    },1000);
}
// If you need to get the result of an asynchronous operation in a function, you must get it by calling a callback function
fn(function(data){
    console.log(data);
})
Copy the code

Array traversal methods, all function as an argument

[Img-tflmkwa7-1584422065213] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-tflmkwa7-1584422065213] [IMG-tflmkwa7-1584422065213] [IMG-tflmkwa7-1584422065213] [IMG-tflmkwa7-1584422065213 e-20200314094620191.png)]

EcmaScript 6

Reference: es6.ruanyifeng.com/

Project case

The directory structure

Node_modules package.json package description file package-lock.json Third-party package version lock file (available later than NPM5) public Public static resource Routes Views Storage view directoryCopy the code

Page template

  • The child templates
  • Template inheritance

Routing design

routing methods The get parameter Post parameters Whether to log in note
/ get Rendering the home page
Login/register () get Render registration page
/register post email,nickname,password Processing registration requests
/login get Render login screen
/login post email,password Processing login requests
/loginout get Handling exit requests

Model design

Function implementation

steps

  • Creating a directory structure
  • Integrate static also – template pages
    • include
    • block
    • extend
  • Design routes for user login, logout and registration
  • User registration
    • First process the content of the client page (form control name, collect form data, initiate request)
    • The service side
      • Gets the data received from the client
      • Operating database
        • If there is an error, send 500 to tell the client that the server is wrong.
        • Others send different response data depending on the business
  • The login
  • exit

Express middleware

Middleware concepts

Reference: expressjs.com/en/guide/us…

[ImG-7kXGH7GL-1584422065213] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [imG-7kXGH7GL-1584422065213] (C:\Users\A\AppData\Roaming\ typora-user-images\imag e-20200316202757617.png)]

Middleware: Divide very complex things into individual pieces and then execute them sequentially. It’s an intermediate process, with inputs and outputs.

To put it more simply, middleware is a (request-to-response invocation method) method.

Data is processed in steps from request to response, and each step is an intermediate processing step.

var http = require('http');
var url = require('url');

var cookie = require('./expressPtoject/cookie');
var query = require('./expressPtoject/query');
var postBody = require('./expressPtoject/post-body');

var server = http.createServer(function(){
	// Parse the get argument in the request address
	// var obj = url.parse(req.url,true);
	// req.query = obj.query;
	query(req,res);	/ / middleware
	
	// Parse the POST argument in the request address
	req.body = {
		foo:'bar'}});if(req.url === 'xxx') {// Process the request. } server.listen(3000.function(){
	console.log('3000 runing... ');
});
Copy the code

The middleware that the same request object passes through is the same request object and response object.

var express = require('express');
var app = express();
app.get('/abc'.function(req,res,next){
	// The req and RES for the same request are the same,
	// Can be stored in front of the following call
	console.log('/abc');
	// req.foo = 'bar';
	req.body = {
		name:'xiaoxiao'.age:18
	}
	next();
});
app.get('/abc'.function(req,res,next){
	// console.log(req.foo);
	console.log(req.body);
	console.log('/abc');
});
app.listen(3000.function() {
	console.log('app is running at port 3000.');
});

Copy the code

[img-naqitvB2-1584422065214] (C:\Users\A\AppData\ Typora\ Typora-user-images \imag) [img-naqitvB2-1584422065214] [IMg-NaqitvB2-1584422065214] (C:\Users\A\AppData\ Typora-user-images \imag e-20200317110520098.png)]

Classification of middleware:

Application-level middleware

Universal matching (middleware that doesn’t care about any request path or request method) :

app.use(function(req,res,next){
    console.log('Time'.Date.now());
    next();
});
Copy the code

Middleware that cares about request paths and request methods:

app.use('/a'.function(req,res,next){
    console.log('Time'.Date.now());
    next();
});
Copy the code

Routing level middleware

Middleware that strictly matches the request path and request method

get:

app.get('/'.function(req,res){
	res.send('get');
});
Copy the code

Post:

app.post('/a'.function(req,res){
	res.send('post');
});
Copy the code

put:

app.put('/user'.function(req,res){
	res.send('put');
});
Copy the code

delete:

app.delete('/delete'.function(req,res){
	res.send('delete');
});
Copy the code

The total

var express = require('express');
var app = express();

// Middleware: handles requests, essentially a function
In Express, there are several categories of middleware

// 1 Middleware that does not care about any request path or request method
// This means that any request will go to the middleware
The middleware itself is a method that takes three arguments
// Request Request object
// Response Indicates the Response object
// next Next middleware
// // Global matching middleware
// app.use(function(req, res, next) {
// console.log('1');
// // When a request enters the middleware
// // Use the next () method if you need to request another method
// next();
// // next is a method that calls the next middleware
// // Note: The next () method also matches when calling the next method (not the one next to it).
// });
// app.use(function(req, res, next) {
// console.log('2');
// });

// // 2 Middleware that cares about request paths
// // Middleware that starts with/XXX
// app.use('/a',function(req, res, next) {
// console.log(req.url);
// });

// 3 Middleware that strictly matches the request method and request path
app.get('/'.function(){
	console.log('/');
});
app.post('/a'.function(){
	console.log('/a');
});

app.listen(3000.function() {
	console.log('app is running at port 3000.');
});

Copy the code

Error handling middleware

app.use(function(err,req,res,next){
    console.error(err,stack);
    res.status(500).send('Something broke');
});
Copy the code

Configure to use 404 middleware:

app.use(function(req,res){
    res.render('404.html');
});
Copy the code

Configure global error handling middleware:

app.get('/a'.function(req, res, next) {
	fs.readFile('.a/bc'.funtion() {
		if (err) {
        	// When next() is passed, it goes directly to the global error-handling middleware method
        	When a global error occurs, we can call next to pass the error object
        	// It is then matched and processed by the global error-handling middlewarenext(err); }})});// Global error handling middleware
app.use(function(err,req,res,next){
    res.status(500).json({
        err_code:500.message:err.message
    });
});
Copy the code

Built-in middleware

  • Express.static (provides static files)
    • Expressjs.com/en/starter/…

Third-party middleware

Reference: expressjs.com/en/resource…

  • body-parser
  • compression
  • cookie-parser
  • mogran
  • response-time
  • server-static
  • session

p.get(‘/’,function(req,res){ res.send(‘get’); });

Post: javascript app.post('/a',function(req,res){res.send('post'); });Copy the code

put:

app.put('/user'.function(req,res){
	res.send('put');
});
Copy the code

delete:

app.delete('/delete'.function(req,res){
	res.send('delete');
});
Copy the code

The total

var express = require('express');
var app = express();

// Middleware: handles requests, essentially a function
In Express, there are several categories of middleware

// 1 Middleware that does not care about any request path or request method
// This means that any request will go to the middleware
The middleware itself is a method that takes three arguments
// Request Request object
// Response Indicates the Response object
// next Next middleware
// // Global matching middleware
// app.use(function(req, res, next) {
// console.log('1');
// // When a request enters the middleware
// // Use the next () method if you need to request another method
// next();
// // next is a method that calls the next middleware
// // Note: The next () method also matches when calling the next method (not the one next to it).
// });
// app.use(function(req, res, next) {
// console.log('2');
// });

// // 2 Middleware that cares about request paths
// // Middleware that starts with/XXX
// app.use('/a',function(req, res, next) {
// console.log(req.url);
// });

// 3 Middleware that strictly matches the request method and request path
app.get('/'.function(){
	console.log('/');
});
app.post('/a'.function(){
	console.log('/a');
});

app.listen(3000.function() {
	console.log('app is running at port 3000.');
});

Copy the code

Error handling middleware

app.use(function(err,req,res,next){
    console.error(err,stack);
    res.status(500).send('Something broke');
});
Copy the code

Configure to use 404 middleware:

app.use(function(req,res){
    res.render('404.html');
});
Copy the code

Configure global error handling middleware:

app.get('/a'.function(req, res, next) {
	fs.readFile('.a/bc'.funtion() {
		if (err) {
        	// When next() is passed, it goes directly to the global error-handling middleware method
        	When a global error occurs, we can call next to pass the error object
        	// It is then matched and processed by the global error-handling middlewarenext(err); }})});// Global error handling middleware
app.use(function(err,req,res,next){
    res.status(500).json({
        err_code:500.message:err.message
    });
});
Copy the code

Built-in middleware

  • Express.static (provides static files)
    • Expressjs.com/en/starter/…

Third-party middleware

Reference: expressjs.com/en/resource…

  • body-parser
  • compression
  • cookie-parser
  • mogran
  • response-time
  • server-static
  • session

Note document: Node learning note extraction code: M05D