当前位置:网站首页>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')
})
边栏推荐
- Global and Chinese market of optical densitometers 2022-2028: Research Report on technology, participants, trends, market size and share
- How to safely eat apples on the edge of a cliff? Deepmind & openai gives the answer of 3D security reinforcement learning
- RB technology stack
- Poap: the adoption entrance of NFT?
- Redis(1)之Redis简介
- Hand drawn video website
- 107. SAP UI5 OverflowToolbar 容器控件以及 resize 事件处理的一些细节介绍
- How to use words to describe breaking change in Spartacus UI of SAP e-commerce cloud
- 142. Circular linked list II
- Take you ten days to easily complete the go micro service series (IX. link tracking)
猜你喜欢

What happened to those who focused on automated testing?

微信小程序:独立后台带分销功能月老办事处交友盲盒

微信小程序:微群人脉微信小程序源码下载全新社群系统优化版支持代理会员系统功能超高收益

Huawei employs millions of data governance experts! The 100 billion market behind it deserves attention

Complex, complicated and numerous: illustration of seven types of code coupling

微信小程序:全新独立后台月老办事处一元交友盲盒

Poap: the adoption entrance of NFT?

How to safely eat apples on the edge of a cliff? Deepmind & openai gives the answer of 3D security reinforcement learning

揭露测试外包公司,关于外包,你或许听到过这样的声音

Wechat applet: independent background with distribution function, Yuelao office blind box for making friends
随机推荐
Yyds dry goods inventory [Gan Di's one week summary: the most complete and detailed in the whole network]; detailed explanation of MySQL index data structure and index optimization; remember collectio
Global and Chinese market of optical densitometers 2022-2028: Research Report on technology, participants, trends, market size and share
Introduction to the gtid mode of MySQL master-slave replication
Call Huawei order service to verify the purchase token interface and return connection reset
SAP UI5 应用开发教程之一百零七 - SAP UI5 OverflowToolbar 容器控件介绍的试读版
Yyds dry goods inventory kubernetes management business configuration methods? (08)
Async/await you can use it, but do you know how to deal with errors?
26.2 billion! These universities in Guangdong Province have received heavy support
[FPGA tutorial case 9] design and implementation of clock manager based on vivado core
[development of large e-commerce projects] performance pressure test - Optimization - impact of middleware on performance -40
C basic knowledge review (Part 3 of 4)
潘多拉 IOT 开发板学习(RT-Thread)—— 实验4 蜂鸣器+马达实验【按键外部中断】(学习笔记)
Global and Chinese market of nutrient analyzer 2022-2028: Research Report on technology, participants, trends, market size and share
实战模拟│JWT 登录认证
抓包整理外篇——————状态栏[ 四]
[wave modeling 1] theoretical analysis and MATLAB simulation of wave modeling
Arbitrum: two-dimensional cost
【海浪建模2】三维海浪建模以及海浪发电机建模matlab仿真
POAP:NFT的采用入口?
Nebula Importer 数据导入实践