Commonly used method

Get Indicates the data transmitted by the client

req.query;

Post Indicates the data transmitted by the client

req.query;

Terminal startup file

Nodemon.\ Locally valid middle key.js

1. Import express
const express = require('express')
Copy the code
2. Create a route object
const router = express.Router()
Copy the code
3. Mount a specific route
router.get('/user/list', (req, res) => {
  res.send('Get user list.')
})
router.post('/user/add', (req, res) => {
  res.send('Add new user.')
})
Copy the code
4. Export the routing object
module.exports = router
Copy the code
Cross-domain modules import and register with middleware before all routing

const cors = require(‘cors’); app.use(cors());

Parse the query string into object form before all routes

app.use(express.urlencoded({ extended: false })); const express = require(‘express’);

Creating a route

const router = express.Router();

Router.get (‘/get’, (req, res) => {const query = req.query; Res. send({status: 0, MSG: ‘GET request successful ‘, data: query,}); }); router.post(‘/post’, (req, res) => { const body = req.body; Res. send({status: 0, MSG: ‘POST request successful ‘, data: body,}); });

Module. exports = router;

module.exports = router;

Install, uninstall, and release third-party packages

1. Initialize the package

NPM init -y #Copy the code

2. The installation package

NPM I package name NPM install Package name NPM I package name. version => NPM I [email protected]Copy the code

3. Install the global package

NPM I Package name -gCopy the code

4. Uninstall packages

NPM uninstall Package name NPM uninstall Package name @ version number NPM uninstall package name -g # Uninstalls the global packageCopy the code

5. The use of NRM

1. NPM I NRM -g # Install NRM 2. NRM ls # Display available image links 3Copy the code

6. Package release

3. NPM publish # Notice that terminal must publish in the root directory of the project 4. NPM unpublish --force # Delete the published packageCopy the code
  1. Install use of NoDemo

    npm i nodemon -g

Fs file system module

Import fs module

const fs = require(‘fs’)

Reads the contents of the specified file

The ⚫ fs.readfile () method, which reads the contents of a specified file

Const fs = require('fs'); const fs = require('fs'); fs.readFile('./Ahigpjbojz.js', 'utf8', function (err, dataStr) { console.log(err); console.log(dataStr); });Copy the code

Writes to the specified file

The ⚫ fs.writefile () method, which is used to write to the specified file

Const fs = require('fs') // 2. Call fs.writefile () to write the contents of the file // Parameter 1: indicates the file storage path // Parameter 2: indicates the contents to be written // parameter 3: indicates the contents of the file. Fs.writefile ('./files/3. TXT ', 'ok123', function(err) {// 2.1 If the file is successfully written, err is null // 2.2 If the file fails to be written, // console.log(err) if (err) {return console.log(' Failed to write file! '+ err.message)} console.log(' File written successfully! ')})Copy the code

Path.join () Path fragment

Using the path.join() method, you can concatenate multiple path fragments into a full path string:

const pathStr = path.join('/a', '/b/c', '.. /.. /', './d', 'e') console.log(pathStr) // \a\b\d\e const pathStr2= fs.readFile(__dirname + '/files/1.txt') console.log(pathStr2)Copy the code

Gets the file extension – suffix in the path

  1. The syntax of path.extname()

Using the path.extname() method, you can obtain the extension part of the path in the following syntax: path.extname(path)

Parameter interpretation:

⚫ path Specifies a path. This parameter is mandatory

⚫ Returns: Returns the resulting extension string

Path to the module

const path = require('path')
Copy the code

Set response headers to solve Chinese garbled characters

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

Creating a server

const http = require('http'); const server = http.createServer(); On ('request', function (req, res) {console.log('Someone visit our web server.'); res.setHeader('Content-Type', 'text/html; charset=utf-8'); Res.end (' hahaha '); }); Server.listen (80, function () {console.log('server running at http://127.0.0.1'); });Copy the code

Exports object

Module. Exports is a complex word to write, so Node provides exports objects to simplify code for sharing members outward. Exports and module.exports refer to the same object by default. Module. exports () : module. Exports () : module. Exports () : module

Third party package download (Taobao mirror. Mirroring is used because of slow outbound network speed.

npm config set registry https://registry.npm.taobao.org
Copy the code

Initialization of the package

NPM init -y will automatically create a JSON file to record the package you installed

Const moment = require(‘moment’) const dt = moment(). Format (‘YYYY-MM-DD ‘+ ‘HH: MM :ss’); Formatting time

Installs the specified version of the package

By default, when the NPM install command is used to install a package, the latest version of the package is automatically installed. If you want to install a specific version of the package, you can specify the specific version by using the @ symbol after the package name, for example:

NPM I [email protected]Copy the code

Express

Express Chinese official website: www.expressjs.com.cn/

Install framework NPM [email protected]

Creating a Server

// install framework NPM I [email protected] // import module const express = require('express'); // Create server const app = express(); / / set to monitor app. Get ('/user '(the req, res) = > {res. Send ({name:' pork son, age: 18, SCX: 'female'}); }); App. Post ('/user '(the req, res) = > {res. Send (' post request success); }); app.listen(3002, function () { console.log('http://localhost:3002'); });Copy the code

Dynamically get matching parameters

app.get('/delete/:id/:name', (req, res) => {
  res.send(req.params);
});
Copy the code
Get Send Send request
http://localhost:3002/delete/999/jike
Copy the code

Terminal startup file

Nodemon.\ Locally valid middle key.js

routing

Examples of routes in Express

/ / mount routing app. Get ('/', (the req, res) = > {res. Send (' hello world. ')}) app. Post ('/', (the req, res) => { res.send('Post Request.') })Copy the code

Modular routing

To facilitate modular route management, Express does not recommend mounting routes directly to the app. Instead, it recommends separating routes into separate modules. The steps for separating routes into separate modules are as follows: ① Create the.js file corresponding to the routing module ② call the express.router () function to create the routing object ③ mount the specific route to the routing object ④ use module.exports to share the routing object ⑤ Use the app.use() function to register the routing module

Creating a Routing Module

Const express = require('express') // 2. Const router = express.router () // 3. Router.get ('/user/list', (req, res) => {res.send(' get user list.')}) router.post('/user/add', (req, res) => { res.send('Add new user.') }) // 4. Exports the route object module.exports = routerCopy the code

Add a prefix to a routing module

Similar to uniformly mounting access prefixes for static resources when hosting static resources, routing modules add prefixes in a very simple way:

// 1. Import router module const router = require('./03.router') // 2. App.use ('/ API ', router)Copy the code

The middleware

// import module const express = require('express'); // Create server const app = express(); App. use((req, res, next) => {res.send(' server in maintenance '); // next(); });}); / / to monitor events app. Get ('/', (the req, res) = > {res. Send (' 999 '); }); // Start the server app.listen(80); console.log('http://localhost');Copy the code

Locally effective middleware

// import module const express = require('express'); // Create server const app = express(); Let mw = (req, res, next) => {console.log(' locally valid middleware '); let mw = (req, res, next) => {console.log(' locally valid middleware '); }; / / create routing app. Get ('/', mw, (the req, res) = > {res. Send (" hello "); }); app.get('/po', mw, (req, res) => { res.send({ age: 20 }); }); app.listen(80); console.log('http://localhost');Copy the code

Error level middleware

You must register after all routes, otherwise they will not work properly

// import module const express = require('express'); // Create server const app = express(); App.get ('/', (req, res) => {throw new Error(' server internal Error 444'); }); Use ((err, req, res, next) => {console.log(err.message); res.send(err.message); }); app.listen(80);Copy the code

Express built-in middleware

Since Express 4.16.0, Express has built three commonly used middleware, which greatly improves the development efficiency and experience of Express projects. / / express. Json; / / express. Json; / / ③ Express.urlencoded parse urL-encoded request body data (compatible, only available in 4.16.0+) ③ Express.urlencoded parse urL-encoded request body data (compatible, only available in 4.16.0+)

Third-party middleware

3. Call app.use() to register and use middleware. The Express. urlencoded middleware built in Express is further encapsulated based on body-Parser, a third-party middleware.

Routing in Express

In Express, routing refers to the mapping between client requests and server processing functions. A route in Express consists of the type of the request, the URL address of the request, and the processing function.

Custom middleware

  1. Requirements description and implementation steps

Manually simulate a middleware like Express.urlencoded to parse form data posted to the server. Implementation steps: ① define middleware ② monitor DATA event of REQ ③ monitor end event of REQ ④ use QueryString module to parse request body data ⑤ mount parsed data object as REq. Body ⑥ Encapsulate custom middleware as module

  1. Defining middleware

Use app.use() to define globally valid middleware as follows:

  1. Listen for reQ data events

Triggered when there is data transmission

Chunks start out as chunks of code that need to be spliced together

// 1. Define a STR string to store the request body data sent by the client. Req. on('data', (chunk) => {STR += chunk})Copy the code
  1. Listen for the end event of reQ

Trigger when data transfer is complete

When the client finally sends all the data to the server, the end event of the REQ is automatically triggered. Therefore, we can get and process the complete request body data in the end event of the REQ. Example code is as follows:

Req.on ('end', () => {console.log(STR)})Copy the code
  1. Parse the request body data using the QueryString module

Node.js has a queryString module built in to handle query strings. The module provides a parse() function that makes it easy to parse query strings into object formats. Example code is as follows:

Const qs = require(' queryString ') const body = qs.parse(STR)Copy the code
  1. Mount the parsed data object as req.body

In order to facilitate the direct access to the request body object parsed by the current middleware in the subsequent business processing process, we mount the parsed data as the custom property of REq, named req.body. Example code is as follows:

Req.on ('end', () => {// console.log(STR) // TODO: Const body = qs.parse(STR) req.body = body next()}) const body = qs.parse(STR) req.body = body next()}Copy the code
  1. Encapsulate custom middleware as modules

In order to optimize the code structure, we can package the customized middleware functions into independent modules. The sample code is as follows:

Const qs = require(' queryString ') const bodyParser = (req, res, Next) => {// Define middleware specific business logic // 1. Define a STR string that stores the string sent by the clientCopy the code

Request body data

Req. on('data', (chunk) => {STR += chunk}) // 3. Req.on ('end', () => {// console.log(STR) // TODO: Module.exports = bodyParser Const body = qs.parse(STR) req.body = body next()})} // module.exports = bodyParserCopy the code

Create a basic API POST excuse

const express = require('express'); // Create a route const router = express.router (); Router.get ('/get', (req, res) => {const query = req.query; Res. send({status: 0, MSG: 'GET request successful ', data: query,}); }); router.post('/post', (req, res) => { const body = req.body; Res. send({status: 0, MSG: 'POST request successful ', data: body,}); }); module.exports = router;Copy the code
Create the startup server and import the cross-domain module

NPM install CORS Installs third-party cross-domain middleware

const express = require('express'); const app = express(); // Cross-domain module import and register middleware const cors = require('cors'); app.use(cors()); // Parse query strings into object form app.use(express.urlencoded({extended: false})); const aa = require('./02.apiGET'); app.use('/api', aa); app.listen(8081); console.log('http://localhost:8081');Copy the code

The database

Select * from users; select * from users; select * from users; select * from users; Password from users -- Insert new data into users table, Insert into users (username, password) values (' Tony Stark ', '098123') -- select * from users -- select * from users Update users set password='888888' where id=4 -- select * from users -- update users set password='888888' where id=4 -- select * from users -- update users set password='888888' Update the user password to admin123 Update users set password='admin123', status=1 where id=2 -- select * from users -- delete from users The user id of 4 - delete from the users where id = 4 - select * from the users, the use of a where clause, the select * from the users where status=1 -- select * from users where id>=2 -- select * from users where username<>'ls' -- select * from users where username! Select * from users where status=0 AND ID <3 -- select * from users where status=0 AND ID <3 -- select * from users where status=0 AND ID <3 -- select * from users where status= 1 AND ID <3 -- select * from users where status= 1 AND ID <3 -- select * from users where status= 1 AND ID <3 -- Select * from users where status=1 or username='zs' -- select * from users where status=1 or username='zs' Select * from users order by status select * from users order by status select * from users order by status Select * from users order by id desc select * from users order by id desc select * from users order by ID desc Select * from users order by status desc, username asc select * from users order by status desc, username asc -- select count(*) from users where status=0 -- alias columns with AS keyword -- select count(*) AS total from users where status=0 -- alias columns with AS keyword -- select count(*) AS total from users where status=0  status=0 -- select username as uname, password as upwd from usersCopy the code

SELECT column name example

Gets all data for a column

To get the contents of columns named “username” and “password” (from a database table named “Users”), use the following SELECT statement:

select username , password from users
Copy the code

The INSERT INTO statement is

The INSERT INTO statement is used to INSERT new rows INTO a data table

  1. INSERT INTO the sample

Insert user data whose username is Tony Stark and password is 098123 into the Users table as shown in the following example:

insert into users (username,password) values ('tony stark','098123')
Copy the code

Basic use of operation database

Where qualification

Where is the qualification, we only mark delete with id? Data,? It’s your custom data

select * from users where status = 1

select * from users where  id > 2

select * from users where  username <> 'admin'
Copy the code

Example Delete data whose ID is 4

Delete user 4 from the Users table as shown in the following example

delete from users where id = 4
Copy the code

AND AND OR operators

  1. grammar

AND AND OR combine two OR more conditions in the WHERE substatement. AND means that more than one condition must be met at the same time, which is equivalent to the && operator in JavaScript, such as if (a! == 10 && a ! = = 20) OR said as long as can meet any conditions, the equivalent of JavaScript | in the | operator, for example the if (a! == 10 || a ! = = 20)

AND to display all values with status 0 AND id less than 3

Use AND to display all users whose status is 0 AND whose ID is less than 3:

select * from users where status=0 and id < 3
Copy the code

Example of the OR operator

The status is 1, or the username is ZS

Use OR to display all users whose status is 1 OR whose username is ZS:

select * from users where status=1 or username='zs'
Copy the code

ORDER BY clause ascending descending multiple sort function alias

  1. grammar

The ORDER BY statement is used to sort the result set BY the specified column. BY default, the ORDER BY statement sorts records in ascending ORDER. If you want to sort the records in descending order, use the DESC keyword.

  1. ORDER BY clause – Ascending sort

Sort the data in the Users table in ascending order by the status field as shown in the following example:

select * from users order by status;
select * from users order by status asc;
Copy the code
  1. ORDER BY clause – Descending sort

Sort the data in the Users table in descending order by the ID field as shown in the following example:

select * from users order by id desc;
Copy the code
  1. ORDER BY clause – multiple ordering

Sort the data in the Users table in descending order according to the status field, then in ascending order according to the alphabetical order of username, as shown in the following example:

select * from users order by status desc, username asc;
Copy the code

COUNT (*) function

  1. grammar

The COUNT(*) function returns the total number of data items in the following syntax:

  1. COUNT (*) sample

Query the total number of data items whose status is 0 in the Users table:

select count(*) from users where status = 0
Copy the code

3. Set aliases for columns using AS

If you want to alias the column names, you can use the AS keyword AS shown in the following example:

select count(*) as total from users where status = 0
Copy the code

Database operations

1. Install the mysql module

The mysql module is a third-party module hosted on NPM. It provides the ability to connect to and manipulate MySQL databases in node.js projects. To use it in your project, run the following command to install mysql as a dependency package for your project:

npm install mysql
Copy the code

Configure the mysql module

Before using the mysql module to operate the mysql database, you must configure the mysql module as follows:

Const mysql = require('mysql') // 2. Const db = mysql.createpool ({host: '127.0.0.1', // IP address of the database user: 'root', // account for logging in to the database password: 'admin123', // database: 'my_db_01', // specify which database to operate on})Copy the code

3. Test whether the mysql module works properly

Query (); db.query();

Db. query('select 1', (err, If (err) return console.log(err. Message) // SQL statement console.log(results)})Copy the code
const mysql = require('mysql'); const db = mysql.createPool({ host: 'localhost', user: 'root', password: 'root', database: 'my_db_1', }); // const SQLSTR = 'select * from users'; // db.query(sqlstr, (err, result) => { // if (err) return console.log(err.message); // console.log(result); / /}); Db.query ('SELECT 1', (err, result) => {// if (err) return console.log(err. Message); // console.log(result); / /}); / / insert data -- shorthand / / const user = {/ / the username: 'bill', / / password: 'XX6666', / /}; // const sqlstr = 'insert into users set ? '; // //user finally concatenated to the above? Query (SQLSTR, user, (err, results) => {// if (err) return console.log(err. Message); // db.query(SQLSTR, user, (err, results) => {// if (err) return console.log(err. // // Check whether the data changed successfully // if (results.affectedrows === 1) {// console.log(' Insert data completed '); / / / /}}); /* const sqlstr1 = 'select * from users'; db.query(sqlstr1, (err, result) => { if (err) return console.log(err.message); console.log(result); }); // const userc = {// id: 6, // password: 'oldtie666', //}; */ / const userc = {// id: 6, // password: 'oldtie666', // // const sqlstr2 = 'update users set ? where id=? '; // db.query(sqlstr2, [userc, userc.id], (err, result) => { // if (err) return console.log(err.message); // if (result.affectedrows === 1) {// console.log(' Data updated successfully!! '); / / / /}}); // const userc = {// id: 8, // password: 'oldtie222', //}; // const sqlstr2 = 'update users set ? where id=? '; // db.query(sqlstr2, [userc, userc.id], (err, result) => { // if (err) return console.log(err.message); // if (result.affectedrows === 1) {// console.log(' Data updated successfully!! '); / / / /}}); // const SQLSTR = 'delete from users where id=? '; // db.query(sqlstr, 9, (err, result) => { // if (err) return console.log(err.message); // if (result.affectedrows === 1) {// console.log(' delete successfully, data with id 9 is permanently lost '); // if (result.affectedrows === 1) {// console.log(' delete successfully, data with ID 9 is permanently lost, data with id 9 is permanently lost '); / / / /}}); Const sqlstr3 = 'update users set status=? where id=? '; db.query(sqlstr3, [1, 10], (err, result) => { if (err) return console.log(err.message); If (result.affectedrows === 1) {console.log(' delete succeeded, status changed to 1 '); }});Copy the code

paging

SELECT art.Id,art.title,art.pub_date,art.state,cate.name FROM ev_articles art LEFT JOIN ev_article_cate cate ON art.cate_id = cate.Id LIMIT 2,2