Knowledge system of Web front end development engineer_ 12_Node.js

1, Router

It is used to manage routes. All routes under a module are put together and finally used by the WEB server.


//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
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
	req.query.price *= 0.9;
	next( );  //Execute later
app.get('/shopping',(req,res)=>{  //Add to cart
	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));


 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
     next(error message) //Give the error to the error handling middleware

//Add error handling middleware to intercept errors in all routes
	//err is the error message passed from the received route
	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({

(3) Execute SQL command

c.query('select * from emp where ename=?',[str],(err,result)=>{
    if(err) throw err;

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({
    connectionLimit:15 //Number of connection pools

(3) query() executes SQL commands

pool.query('select * from emp',(err,result)=>{
    if (err) throw err;

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.

 / / multiple resources / / single resource (V1 version number, EMPs resource name (plural form), 3 number) / / 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:          Filter data of a set of price ranges 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:

     "msg":"Login succeeded"
{ "code":200,"msg":"Login succeeded","data":[ ] }

Recommended interface tool: ApiPost

Node.js end


Keywords: node.js Back-end

Added by Buyocat on Sat, 25 Dec 2021 12:03:49 +0200