1, Router
It is used to manage routes. All routes under a module are put together and finally used by the WEB server.
Usage:
//Under the router: const express = require('express'); //Introducing express const r = express.Router( ); //Create router r.get('/list',(req,res)=>{ //Add route res.send('This is the list of users'); }); module.exports = r; //Export router object
//Under WEB server: const express = require('express'); //Introducing express const userRouter = require('./user.js'); //Introduce user router console.log(userRouter); const app = express( ); //Create web server app.listen(8080,()=>{ //Set port console.log('Server created successfully!'); }); app.use('/user',userRouter); //Use the router to mount all routes under the router to the WEB server, '/ user' is the prefix added for the route
II. Middleware
Between request and response, you can intercept the request or respond. All middleware create servers before use.
1. Application level Middleware
It is a function. Once intercepted, it will execute this function
Format: app Use (URL to intercept, function)
app.use('/shopping',(req,res,next)=>{ //Add Middleware //Get the data passed by get console.log(req.query); req.query.price *= 0.9; next( ); //Execute later }); app.get('/shopping',(req,res)=>{ //Add to cart console.log(req.query); res.send(`Price of goods: ${req.query.price}`); });
2. Routing level Middleware
Use of routers
app. Use (URL to block, router)
3. Built in middleware
It is used to host static resources. If the client hosts static resources (html, css, js, image...), it does not need to respond through the router, but automatically find them in the specified directory.
Format: app Use (express. Static (path of managed directory));
app.use(express.static('./public'));
4. Third party Middleware
It belongs to a third-party module, which needs to be downloaded and installed before use.
5. Error handling Middleware
//Format: in route app.get('/list',(req,res,next)=>{ next(error message) //Give the error to the error handling middleware }); eg: //Add error handling middleware to intercept errors in all routes app.use((err,req,res,next)=>{ //err is the error message passed from the received route console.log(err); res.status(500).send({code:500,msg:'Server side error!'}); //Response error });
3, MySQL module
1. Use steps
(1) Introducing MySQL module
const mysql = require('mysql');
(2) Create a connection object
const c = mysql.createConnection({ host:'127.0.0.1', port:'3306', user:'root', password:'', database:'tedu' });
(3) Execute SQL command
c.query('select * from emp where ename=?',[str],(err,result)=>{ if(err) throw err; console.log(result); });
2. Connection pool
A batch of connections created can be used repeatedly and will be returned after use.
(1) Introducing MySQL module
const mysql = require('mysql');
(2) createPool() creates a connection pool object
const pool = mysql.createPool({ host:'127.0.0.1', port:'3306', user:'root', password:'', database:'tedu', connectionLimit:15 //Number of connection pools });
(3) query() executes SQL commands
pool.query('select * from emp',(err,result)=>{ if (err) throw err; console.log(result); });
4, RESTful interface
An interface is a dynamic resource provided by the back end for the front end (adding, deleting, modifying and querying data), and RESTful is an interface design specification.
1.URL
http://127.0.0.1:8080/v1/emps / / multiple resources
http://127.0.0.1:8080/v1/emps/3 / / single resource (V1 version number, EMPs resource name (plural form), 3 number)
http://127.0.0.1:8080/v1/users/login / / special operations on resources, such as login
2. Request method
Operation methods for resources, including get (get resources), post (create resources), delete (delete resources) and put (modify resources).
3. Filter data
eg:
http://127.0.0.1:8080/v1/products?price1=4000&price2=5000 Filter data of a set of price ranges
http://127.0.0.1:8080/v1/products?pno=1&count=9 Filtering by paging
4. Return results
JSON object: an object in the form of string. The attribute name must be in double quotation marks, and the attribute value must be in double quotation marks, including status code (artificially specified), message and data. The format is as follows:
{ "code":200, "msg":"Login succeeded" } { "code":200,"msg":"Login succeeded","data":[ ] }
Recommended interface tool: ApiPost
Node.js end