directory

Basic use of Express

Obtain the query parameters carried in the URL


		app.get('/'.(req,res) = >{
        // req.query is an empty object by default
        // Client judge? Name = zS&age =20 this query string is sent to the server as a parameter
        // Can be accessed via the req.query object
        // eg : req.query.name req.query.age
        
		console.log(req.query)
    
    })


Copy the code

Get the dynamic parameters in the URL

	
	app.get('/user/:id' , (req,res) = >{
		// This contains the parameter values that are dynamically matched by:
        console.log(req.params)
		         
	})

Copy the code

Express.static () manages static resources

        const express  = require('express')

        const  app =express()

        app.use(express.static('./clock'))


        app.listen(3000.() = >{
          console.log( 'Server successfully started http://localhost:3000');
        })

Copy the code

Mount path prefix


		app.use('/public',express.static('./clock'))Copy the code

Use of routes

Express Route Usage


      const express = require('express')
     const app = express()

      app.get('/'.(req,res) = >{
        res.send('hello get')
      })

      app.post('/'.(req,res) = >{
        res.send('hello post')
      })


     app.listen(80.() = >{
       console.log('http://localhost:80');
     })


Copy the code

Modular routing

		const express = require('express')
        const app = express()

         const router =require('./04-router.js')
         app.use(router)


        app.listen(80.() = >{
          console.log('http://localhost:80');
        })
Copy the code

Routing template

      const express = require('express')
      const router = express.Router()

      router.get('/user/list'.(req,res) = >{
        res.send('Get user list')
      })

      router.post('/user/add'.(req,res) = >{
        res.send('Add new user')})module.exports=router
Copy the code

Example Add a prefix to the route module

		const  userRouter = require('./rouetr/user.js')
        
        app.usre('/api', userRouter)

Copy the code

Express middleware

Global middleware


        app.use((req,res,next) = >{
            console.log('js is the best de voice in the world ');
            next()
        })

        app.get('/'.(req,res) = >{
          res.send('home page')
        })

        app.get('/user'.(req,res) = >{
          res.send('user page')})Copy the code

Local middleware

        const mw =(req,res,next) = >{
           console.log('JS is the most beautiful voice in the world');
           next()
         }

        app.get('/',mw,(req,res) = >{
          res.send('home page')})Copy the code

Locally define multiple middleware

Local middleware executes multiple middleware in front to back order

		 app.get('/',[mw1,mw2],(req,res) = >{
          res.send('home page')})Copy the code

Five considerations for middleware

  1. Be sure to register the middleware before routing
  2. The request sent by the client can be processed by invoking multiple middleware in succession
  3. After executing the middleware business code, don’t forget to call the next () function
  4. To prevent code logic from getting cluttered, don’t write any extra code after calling the next () function
  5. Req and RES objects are shared between multiple middleware when invoked in succession

Classification of middleware

Application levelThe middleware

Middleware that is bound to an app instance via app.use(), app.get(), and app.post() are called application-level middleware

Routing levelThe middleware

Error levelThe middleware

(err,req,res,next); (err,req,res,next);

		const express = require('express')
        const app = express()

          app.get('/'.(req,res) = >{
            throw new Error('An error has occurred inside the server')
            res.send(' ')
          })


          app.use((err,req,res,next) = >{
            console.log('An error has occurred' +err.messsage);
            res.send('Error'+err.message)
          })                      

             app.listen(3000.() = >{
            console.log('http://localhost:3000');
          })

Copy the code

ExpressBuilt-in middleware

  1. Express.static Built-in middleware that quickly hosts static resources
  2. Express. json parses the body of the request in JSON format (version 4.16)
  3. Express. urlencoded parses the request body data in urL-encoded format

Application /json data is encoded in {“title”:”test”,”sub”:[1,2,3]} format

Application/X-wwW-form-urlencoded data format **key1=val1&key2=val2 **

The specific relationship between the two goes to Express middleware

The third partyThe middleware

  • body-parser

    • npm install body-parser
    • Require importing middleware
    • App.use () registers to use middleware

    Express’s built-in Express.Urlencoded middleware is further encapsulated based on the body-Parser third-party middleware

    		const express = require('express')
            const parser = require('body-parser')
            const app = express()
              app.use(parser.urlencoded({extended:false}))      
    
              app.post('/user'.(req,res) = >{
                res.send('hello my friend')
                console.log(req.body);
                })
    
                app.listen(3000.() = >{
                console.log('http://localhost:3000');
              })
    Copy the code

Custom middleware

  • Manually simulate an express.urlencoded parse POST submission to the server form
    • Defining middleware
    • Listen for reQ data events
    • Use the QueryString module to parse the request body data
    • Mount the parsed data object as res.body
    • Custom middleware encapsulated as modules

		const express = require('express')
        const app = express()
        const qs =require('querystring')        
        // Call queryString.parse () to convert a string into an object
		// Json.stringGify () converts a JSON object to a string
        app.use((req,res,next) = >{
          let str=' '
          req.on('data'.(chunk) = >{		// Listen for data events to concatenate the data transmitted each time
            str += chunk

          })
          req.on('end'.() = >{
           const body=qs.parse(str)			
            req.body=body
           next()
          })

        })
        app.post('/user'.(req,res) = >{
          res.send(req.body)

        })

            app.listen(3000.() = >{
            console.log('http://localhost:3000');
          })
Copy the code

Encapsulation of custom middleware

		const express = require('express')
        const custombodyparser = require('./11.custombodyparser')   
        // Call the wrapped function to format the data
        const app = express()                              

        app.use(custombodyparser)
        app.post('/user'.(req,res) = >{
          res.send(req.body)
        })

            app.listen(3000.() = >{
            console.log('http://localhost:3000');
          })
Copy the code

		const qs =require('querystring')   
         const custombodyparser= (req,res,next) = >{
          let str=' '
          req.on('data'.(chunk) = >{
            str += chunk

          })
          req.on('end'.() = >{
           const body=qs.parse(str)
            req.body=body
           next()
          })
        }
        module.exports= custombodyparser
Copy the code

Use the Express write interface

  1. Create the base server

  2. Create the API routing module

  3. Write the GET interface

  4. Writing a POST interface

        const express =require('express')
        const router =express.Router()
    
        router.get('/get'.(req,res) = >{
         let query= req.query
          res.send({
            status:0.msg:'Get request successful'.data:query
          })
        })
    
        router.post('/post'.(req,res) = >{
          let body =req.body
          res.send({
            status:0.msg:'Post request successful'.data:body
          })
        })
    
    
        module.exports= router
    Copy the code

The CORS interface is cross-domain

Interface cross-domain problems

  1. CORS (mainstream solution, recommended)
  2. JSONP (defective, only support GET requests)

Use CORS middleware to solve cross-domain problems

Cors is the third-party middleware of Express. You can install and configure CORS middleware to solve cross-domain problems

  1. npm i cors
  2. const cors =require(‘cors’)
  3. Call app.use(cors()) before routing

Note in CORS (1)

  1. Call app.use (cors()) // cors() before routing
<! DOCTYPEhtml>
<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>
</head>
<script src="https://cdn.staticfile.org/jquery/1.10.0/jquery.min.js"></script>
<body>
    <button id="btnGET">GET</button>
    
    <button id="btnPOST">POSt</button>
</body>
<script>
  //get 
 $('#btnGET').on('click'.() = >{
  $.ajax({
    type:'GET'.url:'http://localhost:3000/api/get'.data: {name:'zt'.age:20.gender:'male'
    },
    success(res){
      console.log(res); }})})//post 

 $('#btnPOST').on('click'.() = >{
  $.ajax({
    type:'POST'.url:'http://localhost:3000/api/post'.data: {bookname:'Water Margin'.autoname:'Shi Nai am'
    },
    success(res){
      console.log(res); }})})</script>
</html>
Copy the code
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())

app.use(express.urlencoded({extended:false})) 
const apiRouter = require('./13router')
app.use('/api',apiRouter)

                                         
                                                                       
 app.listen(3000.() = >{
   console.log('http://localhost:3000');
  })
Copy the code
const express =require('express')
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) = >{
  let body =req.body
  res.send({
    status:0.msg:'Post request successful'.data:body
  })
})


module.exports= router
Copy the code

Note in CORS (2)

  1. CORS is mainly configured on the server. The client does not need to do any additional configuration to request to enable the CORS interface
  2. CORS is compatible in browsers

CORS Response header access-control-allow-origin

​ Access-Control-Allow-Origin: |

Eg: res.setheader (‘ access-control-allow-origin ‘,’itcast.cn’) // Only Allow requests from itcast.cn

Res.setheader (‘ access-control-allow-Origin ‘, ‘*’) // Allow any domain to initiate a request

Review the jSOP

The concept browser requests data from the server via the SRC attribute of the script tag and the server returns a call to a function

This way of requesting data is called JSONPCopy the code

Features:

  1. JSONP is not an AJAX request because it doesn’t use XMLHTTPRequest
  2. JSONP supports only GET requests but not POST and DELETE requests

Precautions for creating a JSONP interface

If CORS cross-domain resource sharing has been configured in the project, to prevent conflicts, you must declare the JSONP interface before configuring CORS middleware, otherwise

JSONP interfaces will be processed as CORS enabled interfaces

		app.get('/api/jsonp'.(req,res) = >{})
		app.use(cors())
		app.get('/api/get'.(req,res) = >{})

Copy the code

Make a JSONP request using jquery in a web page

Call the $.ajax() function to provide JSONP configuration options to initiate JSONP requests

		$('#btnJSONP').on('click'.() = >{
            $.ajax({
                method:'GET'.url:'http://localhost:3000/api/jsonp'.dataType:'jsonp'./ / is very critical
                success(){
                    console.log(res)
                }                                          
            })                     
        })
Copy the code
		app.get('/api/jsonp'.(req,res) = >{
            const funcName =req.query.callback
            const data = {  name : 'zs' ,  age: 22 }
            
            const scriptStr = `${funcName}(The ${JSON.stringify(data)}) `  // Return call cb(data)
            res.send(scriptStr)
        })

Copy the code