当前位置:网站首页>Express routing, express middleware, using express write interface
Express routing, express middleware, using express write interface
2022-07-05 01:20:00 【Tianfubao 615】
( One )Express route
One 、 The concept of routing
1、 What is routing

2、 Real life routing

3、Express The routing

4、Express Examples of routing in

5、 Routing matching process

Two 、 Use of routes
1、 The simplest use ( Rarely used )

const express = require('express')
const app = express()
// Mount route
app.get('/' , (req,res )=> {
res.send('hello world.')
})
app.post('/' , (req , res) => {
res.send('Post Request')
})
app.listen(8080 , ()=> {
console.log('http://127.0.0.1:8080');
})

2、 Modular routing

3、 Create routing module 
// This is the routing module
// 1. Import express
var express = require('express')
// 2. Create routing objects
var router = express.Router()
// 3. Mount specific routing
router.get('/user/list' , (req,res)=> {
res.send('Get user list')
})
router.post('/user/add' , (req,res) => {
res.send('Add new user')
})
// 4. Export routing objects out
module.exports = router4、 Register routing module

var express = require('express')
var app = express()
// app.use(express.static('./files'))
// 1. Import routing module
var router = require('./03-router')
// 2. Register routing module
app.use(router)
// Be careful :app.use() Function function , Is to register the global middleware
app.listen(8080 , (req,res)=> {
console.log('http://127.0.0.1:8080');
})
5、 Prefix routing module

( Two )Express middleware
One 、 Middleware concept
1、 What is Middleware

2、 Real life examples

3、Express Call process of Middleware

4、Express Middleware format

5、next Function function

Two 、 Express The first experience of middleware
1、 Define middleware functions

var express = require('express')
var app = express()
// Define a box of the simplest middleware functions
var mw = function(req, res , next){
console.log(' This is the simplest middleware function ');
// Put the circulation relationship , Forward to the next middleware or route
next()
}
app.listen(8080 , (req,res) => {
console.log('http://127.0.0.1:8080');
})2、 Globally effective middleware

var express = require('express')
var app = express()
// Define a box of the simplest middleware functions
var mw = function(req, res , next){
console.log(' This is the simplest middleware function ');
// Put the circulation relationship , Forward to the next middleware or route
next()
}
// take mw Register as a globally effective middleware
app.use(mw)
app.get('/' , (req,res) => {
console.log(' Called / This route ');
res.send('Home Page')
})
app.post('/user' , (req,res) => {
console.log(' Called /user This route ');
res.send('User Page')
})
app.listen(8080 , (req,res) => {
console.log('http://127.0.0.1:8080');
})

3、 Define a simplified form of global middleware

var express = require('express')
var app = express()
// Define a box of the simplest middleware functions
// var mw = function(req, res , next){
// console.log(' This is the simplest middleware function ');
// // Put the circulation relationship , Forward to the next middleware or route
// next()
// }
// // take mw Register as a globally effective middleware
// app.use(mw)
// This is a simplified form of defining global middleware
app.use(function(rew,res , next){
console.log(' This is the simplest middleware function ');
next()
})
app.get('/' , (req,res) => {
console.log(' Called / This route ');
res.send('Home Page')
})
app.post('/user' , (req,res) => {
console.log(' Called /user This route ');
res.send('User Page')
})
app.listen(8080 , (req,res) => {
console.log('http://127.0.0.1:8080');
})4、 The role of middleware

var express = require('express')
const req = require('express/lib/request')
var app = express()
// This is a simplified form of defining global middleware
app.use(function(rew,res , next){
// Get the time when the request arrived at the server
const time = Date.now()
// by req object , Mount custom properties , So as to share time with later All routes
req.StartTime = time
next()
})
app.get('/' , (req,res) => {
res.send('Home Page' +req.StartTime )
})
app.post('/user' , (req,res) => {
res.send('User Page' +req.StartTime )
})
app.listen(8080 , (req,res) => {
console.log('http://127.0.0.1:8080');
})5、 Define multiple global middleware

const express = require('express')
const app = express()
// Define two Middleware in succession
// Define the first global middleware
app.use((req,res , next) => {
console.log(' The first global middleware is called ');
next()
})
// Define the second global middleware
app.use((req,res , next) => {
console.log(' The second global middleware is called ');
next()
})
// Define a route
app.get('/user' , (req,res) => {
res.send('User Page')
})
app.listen(8080 , (req,res) => {
console.log('http://127.0.0.1:8080');
})
6、 Partially effective middleware

// Import express modular
const express = require('express')
// establish express Server instance of
const app = express()
// 1. Define middleware functions
const mw1 = (req,res ,next) => {
console.log(' The partially effective middleware is called ');
}
// 2、 Create route
app.get('/' ,mw1, (req,res) => {
res.send('Home Page')
})
app.post('/user' , (req,res) => {
res.send('User Page')
})
// call app.listen Method , Specify the port number and start web service
app.listen(8080 , function(){
console.log('Express server running at http://127.0.0.1:8080');
})
7、 Define multiple local middleware

8、 Learn about middleware 5 There are two points for attention

3、 ... and 、 Classification of middleware

1、 Application level middleware

2、 Routing level middleware

3、 Error level middleware

// Import express modular
const express = require('express')
// establish express Server instance of
const app = express()
// 2. Create route
app.get('/', (req, res) => {
// 1.1 Man made mistakes
throw new Error(' An error occurred inside the server !')
res.send('Home page.')
})
// 2. Middleware that defines error levels , Catch exception errors for the entire project , To prevent the program from crashing
app.use((err , req ,res ,next) => {
console.log(' Something went wrong !' + err.message);
res.send('Error' +err.message)
})
// call app.listen Method , Specify the port number and start web The server
app.listen(8080, function () {
console.log('Express server running at http://127.0.0.1:8080')
})
4、Express Built-in middleware 
// Import express modular
const express = require('express')
// establish express Server instance of
const app = express()
// Except for error level middleware , Other levels of Middleware , Must be configured before routing
// adopt express.json () This middleware , Parse... In the form JSON Formatted data
app.use(express.json())
// adopt express.urlencoded () This middleware , To parse... In the form url-encoded Format data
app.use(express.urlencoded({extended: false}))
// Define routes
app.post('/user' , (req,res) => {
// The server can use req.body This attribute , To receive the request body data sent by the client
// By default , If you don't configure middleware to parse form data , be req.body Default equal to undefined
console.log(req.body);
res.send('User Page')
})
app.post('/book' , (req,res) => {
// On the server side , Can pass req.body To get JSON Format Form data and URL-encoded Formatted data
console.log(req.body );
res.send('ok')
})
// call app.listen Method , Specify the port number and start web The server
app.listen(8080, function () {
console.log('Express server running at http://127.0.0.1:8080')
})
// call app.listen Method , Specify the port number and start web The server
app.listen(8080, function () {
console.log('Express server running at http://127.0.0.1:8080')
})
5、 Third party middleware

Four 、 Custom middleware
1、 Requirements description and implementation steps

2、 Define middleware

3、 monitor req Of data event 
4、 monitor req Of end event 
5、 Use querystring The module parses the request body data 
6、 Mount the parsed data object as req.body
7、 Encapsulate the custom middleware into modules

// Import Node.js Built in querystring modular
const qs = require('querystring')
const bodyParser = (req, res ,next) => {
// Define the specific business logic of middleware
// 1. Define a str character string , It is specially used to store the request body data sent by the client
let str = ''
// 2. monitor req Of data event
req.on('data' , (chunk) => {
str = chunk
})
// 3. monitor req Of end event
req.on('end' , () => {
// stay str The complete request body data is stored in the
console.log(str);
// TODO : Put the request body data in string format , Resolve to object format
const body =qs.parse(str)
// console.log(body);
req.body = body
next()
})
}
module.exports = bodyParser
// Import express modular
const { log } = require('console')
const express = require('express')
// establish express Server instance of
const app = express()
// This is the middleware for parsing form data
// 1. Import your own encapsulated middleware module
const customBodyParser = require('./14-custom-body-parser')
// 2. The customized middleware functions , Register as a globally available middleware
app.use( customBodyParser)
// Define routes
app.post('/user' , (req,res) => {
res.send(req.body)
})
// call app.listen Method , Specify the port number and start web The server
app.listen(8080, function () {
console.log('Express server running at http://127.0.0.1:8080')
})
( 3、 ... and ) Use Express Write the interface
One 、 Create a basic server

Two 、 establish API Routing module

3、 ... and 、 To write GET Interface

Four 、 To write POST Interface 
const express = require('express')
const router = express.Router()
// Mount the corresponding route here
router.get('/get' ,(req,res) => {
// adopt req.query Get the client through the query string , Data sent to server
const query = req.query
// call res.send () Method , Respond to the results of processing to the client
res.send({
status : 0, // 0 : Indicates successful processing , 1 : Indicates that the processing failed
msg : 'GET The request is successful ' , // Description of the State
data : query // Data that needs to be responded to the client
})
})
// Definition POST Interface
router.post('/post' , (req,res) => {
// adopt req.body Get the... Contained in the request body url-encoded Formatted data
const body = req.body
// call res.send() Method , Respond to client results
res.send({
status : 0 ,
msg : 'POST The request is successful ' ,
data :body
})
})
module.exports = router// Import express modular
const e = require('express')
const express = require('express')
// establish express Server instance of
const app = express()
// Configure middleware for parsing form data
app.use(express.urlencoded({extended:false}))
// Import routing module
const router = require('./16-apiRouter')
// Register the routing module to app On
app.use('/api' , router)
// call app.listen Method , Specify the port number and start web The server
app.listen(8080, function () {
console.log('Express server running at http://127.0.0.1:8080')
})

5、 ... and 、CORS Cross-domain resource sharing
1、 Cross domain problem of interface

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<button id="get">GET</button>
<button id="post">POST</button>
<script>
$(function(){
// 1. test GET Interface
$('#get').on('click ' , function(){
$.ajax({
type : 'GET' ,
url : 'http://127.0.0.1:8080/api/get' ,
data : {name : 'zs' , age: 30} ,
success: function(res) {
console.log(res);
}
})
})
// 2. test POST Interface
$('#post').on('click ' , function(){
$.ajax({
type : 'POST' ,
url : 'http://127.0.0.1:8080/api/post' ,
data : {bookname : ' Water margin ' , author: ' Shi Naian '} ,
success: function(res) {
console.log(res);
}
})
})
})
</script>
</body>
</html>
2、 Use cors Middleware solves cross domain problems

// Import express modular
const e = require('express')
const express = require('express')
// establish express Server instance of
const app = express()
// Configure middleware for parsing form data
app.use(express.urlencoded({extended:false}))
// Be sure to before routing , To configure cors This middleware , So as to solve the problem of interface cross domain
const cors = require('cors')
app.use(cors())
// Import routing module
const router = require('./16-apiRouter')
// Register the routing module to app On
app.use('/api' , router)
// call app.listen Method , Specify the port number and start web The server
app.listen(8080, function () {
console.log('Express server running at http://127.0.0.1:8080')
})

3、 What is? cors

4、cors Precautions for

5、CORS Response head - Access-Control -Allow-Origin


6、CORS Response head - Access-Control -Allow-Headers

7、CORS Response head - Access-Control -Allow-Methods

8、CORS Classification of requests

9、 A simple request

10、 Pre inspection request

11、 The difference between simple request and pre inspection request

6、 ... and 、JSONP Interface
1、 review JSONP The concept and characteristics of

2、 establish JSONP Interface precautions

3、 Realization JSONP Interface steps

4、 Realization JSONP The specific code of the interface

5、 Use... In web pages jQuery Sponsored JSONP request

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<button id="get">GET</button>
<button id="post">POST</button>
<button id="Delete">Delete</button>
<button id="JSONP">JSONP</button>
<script>
$(function(){
// 1. test GET Interface
$('#get').on('click ' , function(){
$.ajax({
type : 'GET' ,
url : 'http://127.0.0.1:8080/api/get' ,
data : {name : 'zs' , age: 30} ,
success: function(res) {
console.log(res);
}
})
})
// 2. test POST Interface
$('#post').on('click ' , function(){
$.ajax({
type : 'POST' ,
url : 'http://127.0.0.1:8080/api/post' ,
data : {bookname : ' Water margin ' , author: ' Shi Naian '} ,
success: function(res) {
console.log(res);
}
})
})
// 3. Bind click event handler for delete button
$('#Delete').on('click' , function(){
$.ajax({
type: 'DELETE' ,
url: 'http://127.0.0..1:8080/api/delete' ,
success: function(res){
console.log(res);
}
})
})
// 4. by JSONP Button binding click event handler
$('#JSONP').on('click' , function(){
$.ajax({
type : 'GET' ,
url :'http://127.0.0.1:8080/api/jsonp',
dataType: 'jsonp' ,
success:function(res){
console.log(res);
}
})
})
})
</script>
</body>
</html>// Import express modular
const e = require('express')
const express = require('express')
// establish express Server instance of
const app = express()
// Configure middleware for parsing form data
app.use(express.urlencoded({extended:false}))
// Must be configured CORS Before Middleware , To configure JSONP The interface of
app.get('/api/jsonp' , (req,res) => {
// TODO: Definition JSONP Interface specific implementation interface
// 1. Get the name of the function
const funcName =req.query.callback
// 2. Define the data object to send to the client
const data = {name : 'zs ' , age : 20}
// 3. Splice the call of a function
const scriptStr = `${funcName}(${JSON.stringify(data)})`
// 4. Put the concatenated string , Respond to clients
res.send(scriptStr)
})
// Be sure to before routing , To configure cors This middleware , So as to solve the problem of interface cross domain
const cors = require('cors')
app.use(cors())
// Import routing module
const router = require('./16-apiRouter')
// Register the routing module to app On
app.use('/api' , router)
// call app.listen Method , Specify the port number and start web The server
app.listen(8080, function () {
console.log('Express server running at http://127.0.0.1:8080')
})
边栏推荐
- SAP UI5 应用开发教程之一百零六 - 如何提高 SAP UI5 应用路由 url 的可读性试读版
- Applet live + e-commerce, if you want to be a new retail e-commerce, use it!
- La jeunesse sans rancune de Xi Murong
- Intel sapphire rapids SP Zhiqiang es processor cache memory split exposure
- Single step debugging of master data reading of SAP commerce cloud products
- Global and Chinese markets for industrial X-ray testing equipment 2022-2028: Research Report on technology, participants, trends, market size and share
- [FPGA tutorial case 10] design and implementation of complex multiplier based on Verilog
- Discrete mathematics: propositional symbolization of predicate logic
- Package What is the function of JSON file? What do the inside ^ angle brackets and ~ tilde mean?
- How to safely eat apples on the edge of a cliff? Deepmind & openai gives the answer of 3D security reinforcement learning
猜你喜欢

JS implementation determines whether the point is within the polygon range

Game 280 of leetcode week

Basic operations of database and table ----- create index

Yyds dry goods inventory kubernetes management business configuration methods? (08)

Basic operations of database and table ----- delete index

【海浪建模1】海浪建模的理论分析和matlab仿真

Expose testing outsourcing companies. You may have heard such a voice about outsourcing

JS implementation determines whether the point is within the polygon range

Innovation leads the direction. Huawei Smart Life launches new products in the whole scene

Senior Test / development programmers write no bugs? Qualifications (shackles) don't be afraid of mistakes
随机推荐
Intel sapphire rapids SP Zhiqiang es processor cache memory split exposure
LeetCode周赛 + AcWing周赛(T4/T3)分析对比
Async/await you can use it, but do you know how to deal with errors?
Global and Chinese markets for industrial X-ray testing equipment 2022-2028: Research Report on technology, participants, trends, market size and share
Database postragesq BSD authentication
19. Delete the penultimate node of the linked list
The most complete regular practical guide of the whole network. You're welcome to take it away
Discrete mathematics: reasoning rules
Query for Boolean field as "not true" (e.g. either false or non-existent)
Call Huawei order service to verify the purchase token interface and return connection reset
小程序容器技术与物联网 IoT 可以碰撞出什么样的火花
The performance of major mainstream programming languages is PK, and the results are unexpected
POAP:NFT的采用入口?
What happened to those who focused on automated testing?
SAP UI5 应用的主-从-从(Master-Detail-Detail)布局模式的实现步骤
Analysis and comparison of leetcode weekly race + acwing weekly race (t4/t3)
Blue Bridge Cup Square filling (DFS backtracking)
When the industrial Internet era is truly developed and improved, it will witness the birth of giants in every scene
【FPGA教程案例10】基于Verilog的复数乘法器设计与实现
Daily question brushing record (13)