express framework learning

Keywords: html5 html css

express is a node framework

It prepares you for all the back-end needs to do

Encapsulate most behaviors into methods (services)

An interface location is reserved, and many plug-ins can be registered directly

use

1 download using npm install express

2 import using const express = require('express')

3 create service

=>After importing, it is a function, and the execution will return a service

=>express()

=>The return value is a service

Listening port   listen(8000,()=>{})

4. Rely on express to create a service to listen to the port

express return response

The express framework classifies all requests

Sort by request

get,post,delete,patch,put....

Use services to call

The parameters of these methods are consistent

xxx('path ', callback) receives a req,res in each request processing function

req indicates the information of this request and res the information of this response

res has an additional method called send() and retains the end method

The end method can only return string types

The send method will automatically convert to json format when you return another data type

Back end routing

Routing: give different responses according to different requests from the front end

When dealing with business logic, we can classify all requests

express initially implemented routing as app. Get(), app. Post()

const express =require('express')

const app =express()

//The separate processing of each request is called back-end routing
app.get('/a',(req,res)=>{
  res.send({name:'Jack',age:18})
})
app.post('/a',(req,res)=>{
  res.send('I took it post Requested/a Path identifier')
})
app.delete('/a',(req,res)=>{
  res.send('I'm from delete request')
})
app.listen(3000,()=>console.log('Run on 3000 port'))

express routing table

The express framework has a separate api and does not perform routing processing. It just configures a separate table and gives the configured table to the service, so that the service can route according to the configuration of this table

The express object has a member called Router, which is a function. When this function is executed, it will return a routing table (an empty table). You can configure various routes on this table

After getting an empty table, add content to the table

get(),post(),delete(),...

Syntax: XXX (path identifier, callback function)

Tell the app service the form to use

Method: app.use('What to use ')

In this way, the routing table configuration can be taken out separately in the way of modular development

Classify requests

Classified by business logic

  =>  User related

  => Commodity related

. . . .

//Task: create a table
const express = require('express')

//Create table
const router = express.Router()

//Add content to table

router.get('/getInfo',(req,res)=>{
  res.send('I am get request /getInfo Path identifier')
})
router.post('/login',(req,res)=>{
  res.send('I am get request /login Path identifier')
})
router.post('/reg',(req,res)=>{
  res.send('I am get request /reg Path identifier')
})
//Export table
module.exports =router

Problem mounting routing table

        app.use is executed sequentially

        When you mount multiple tables, the following route will appear and run empty in the previous table

        After you mount multiple routing tables, you'd better use app.use for classification

                Don't come in if it doesn't belong to you  

        It can be agreed

        User related route, identifier starts with / users

        Route related to goods, identifier starts with / goods

app.use()

=>The first parameter is optional, and the default is "*". You can write a string to represent the identifier starting with this string, and use the content mounted later

=>The second parameter is to mount the content

const express =require('express')
//Import the prepared routing table
const userRouter =require('./route/user')
const goodRouter =require('./route/goods')
const app =express()
//Tell app which table to use
//Only requests starting with / users will use this table
app.use('/user',userRouter)
app.use('/goods',goodRouter)
app.listen(3000,()=>console.log('Run on 3000 port'))

Static resource allocation

Front end static resources

        => Front end uses js css images videos... Third party

        => Static resources should start with / public uniformly. express provides us with a method of static resources

          It is required to start with unified / public

          The rest will be written in the directory after public

express.static ('static resource storage path ')   

        Mount the following static resources at the front of all routing tables

        When configuring static resources, it is best to configure two

        1. Write your own static resources

        2. Third party static resources

const express = require('express')
const viewsRouter = require('./route/views')
const app =express()
//Mount static resources
//All / public beginners will go to the public folder to find the content
//Follow the content behind your request path to find it
app.use('/public',express.static('./public'))
app.use('/node_modules',express.static("../node_modules"))
app.use('/views',viewsRouter)

app.listen(3000,()=>console.log('Run on 3000 port'))

Processing of receiving parameters

express handles the parameters carried behind the address separately

Parameters in get form

A member called quert is added to the req, which is the parsed request parameters

express doesn't handle body, but it has an interface

The plug-in is called body parser. It is a plug-in dedicated to parsing the request body, but it cannot parse the file

express has this plug-in built in

use

1. Use the built-in express to resolve the request before entering the route when it is mounted on the service

Mount express.urlencoded()

After mounting, a new member body will be added to req

Inside is the request body information of all requests

2. Use the body parser plug-in

const express = require('express')
const testRouter =require('./route/test')
const app =express()
app.use(express.urlencoded())



app.use(testRouter)
app.listen(3000,()=>console.log('Run on 3000 port'))



//Test routing table
const router = require('express').Router()

router
  .get('/a',(req,res)=>{
    //Prepare to receive parameters
    const {url,query} =req
    console.log(url);
    console.log(query);
    res.send({
      message:'Parameters received successfully!',
      param:query
    })
  })
  .post('/a',(req,res)=>{
    console.log(req.body);
    res.send({
      message:'receive post Parameter request succeeded!',
      body:req.body
    })
  })
  module.exports =router

File upload

At the front end, the local img video and audio files are sent to the server, which stores them in the server and the file address in the database

The front end passes the file to the back end

Direct form upload

Native JS upload

JQuery upload file

<!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>
</head>

<body>
  <!-- Form direct upload
  form Label settings
  action Set server address
  method Post mode
  enctype application/mutilpart
  enctype In the request header content-type
  mutilpart Set upload as binary stream
  input 
    type choice file
    name set name
  -->
  <form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="pic">
    <input type="text" name="username">
    <button>upload</button>
  </form>
</body>

</html>
<!-- Primordial js upload -->
<!-- <script>
  /* Native js upload requires HTTP/2.0 technology and provides a built-in constructor called FormData()
     Syntax: new FormData(form element)
     Returns a value containing all the elements with the name attribute in the form element
  */
  // 1. Get element binding event
  const form =document.querySelector('form')
  form.addEventListener('submit',function(e){
    e.preventDefault()
    //2. Get the documents
    const formData =new FormData(this)
    //3. Normal ajax sending
    const xhr =new XMLHttpRequest()
    xhr.open('POST','address')
    //There is no need to set the request header separately
    //Because formData automatically sets the request header
    xhr.send(formData)

    xhr.onload=()=>{

    }
  })
</script> -->
<!-- jquery Upload file -->
<script src="../../node_modules/jquery/dist/jquery.min.js"></script>
<script>
  /*
    jquery Upload and native js are basically the same
    Binding event
    Get the data using FormData()
    Using $. ajax()

    Problem: formData will automatically set the request header, and jquery will also
    jquery It will be set to application/x-www-form-urlencoded by default
    formData Will be sent in the form of a binary stream
    jquery All the data will be formatted directly into key = value & key = value
  */
  $('form').submit((e) => {
    e.preventDefault()
    const formData = new FormData($('form')[0])

    $ajax({
      method: "POST",
      url: 'http://localhost:3000/upload',
      data: formData,
      contentType: false,//Don't move the request header, upload directly
      processData: false,//Don't worry about the data, upload it directly
      success(res) {
        console.log(res);
      }
    })

  })
</script>

The back end receives the file and stores it

        Single file upload

        Single name multi file upload

        Multiple file upload

//Single file upload simple
/*1.Cross domain problem
  Download a package cors npm install cors
  2.receive files
  Prepare folders and store uploaded files on the server
  Need a plug-in help
  multer
  Download npm install multer
  to configure
  Import
  You need to configure a receiver with multer
  multer({dest:'Path to store files'})
  Use the receiver to receive files
  Which route needs to receive files is configured on which route
  It is written after the route identifier and before the route processing function
  Receiver. single('key of the file uploaded by the front end)
  In the routing function
  There will be an additional information file on the req, which is the information of the uploaded file
  Note: your files will be stored, but there is no suffix and named randomly
*/
// const express = require('express')
// const router =express.Router()
// //Import cors plug-in
// const cors = require('cors')
// //Import the filter plug-in
// const multer = require('multer')
// //Use multer to generate a receiver
// //For configured reception, store the received files in the specified directory
// const fileUpload = multer({dest:'./uploads/'})
// const app = express()
// //Mount cors to cross domain
// app.use(cors())
// //Configure on the required route
// router.post('/upload',fileUpload.single('pic'),(req,res)=>{
//   console.log('receive request ');
//   console.log(req.file);
// })
// app.use(router)
// App.listen (3000, () = > console.log ('port 3000 '))


//Single file upload complex version
/* 
  Sir into a warehouse information
  multer.diskDtirage({Configuration})
    => destitnation:function(){} Set storage path
    => filename:function(){} Set file name
  Return value: warehouse information
  Generate a receiver using multer
  A warehouse information is configured in the receiver
  Syntax: multer({storage: warehouse information})
  */ 
const express = require('express')
const path = require('path')
const router =express.Router()
//Import cors plug-in
const cors = require('cors')
//Import the filter plug-in
const multer = require('multer')
//Use multer to generate a warehouse information
const storage =multer.diskStorage({
  destination:function(req,file,cb){
    //req, this request information
    //file, this request path
    //cb, callback function, use the callback function to set the storage path
    //The first parameter is null, indicating that the binary file should not be modified
    cb(null,'./uploads/')
  },
  filename:function(req,file,cb){
    //req, this request information
    //File, file information uploaded this time
    //cb, callback function, which sets the file name through the callback function
    console.log(file);
    //Take out the suffix from the file information and splice random numbers
    const tmp =path.extname(file.originalname)
    cb(null,`pic_${new Date().getTime()}-${Math.random().toString().slice(2)}${tmp}`)
  }   
})
// Configure receiver with warehouse information
const fileUpload = multer({storage})
const app = express()
//Mount cors to cross domain
app.use(cors())
//Configure on the required route
router.post('/uploads',fileUpload.single('pic'),(req,res)=>{
  console.log('Receive request');
  console.log(req.file);
})
app.use(router)
app.listen(3000,()=>console.log('Port 3000'))
// The single method is dedicated to receiving a single file. One file is assigned to one name
// The array method is used to receive multiple files. One name is matched with multiple files. / / multiple files with a single name
// The field method is used to receive multiple files. Multiple names are matched with multiple files. / / multiple names are called multiple files
//req.file cannot be received in the later routing processing function
//File is a single file
//Files are multiple files (in the form of an array, which stores the information of each file)
//Single name multi file
// const express = require('express')
// const router =express.Router()
// //Import cors plug-in
// const cors = require('cors')
// //Import the filter plug-in
// const multer = require('multer')
// //Use multer to generate a receiver
// //For configured reception, store the received files in the specified directory
// const fileUpload = multer({dest:'./uploads/'})
// const app = express()
// //Mount cors to cross domain
// app.use(cors())
// //Configure on the required route
// router.post('/upload',fileUpload.array('pic'),(req,res)=>{
//   console.log('receive request ');
//   console.log(req.files);
// })
// app.use(router)
// App.listen (3000, () = > console.log ('port 3000 '))
//Multiple files
const express = require('express')
const path = require('path')
const router =express.Router()
//Import cors plug-in
const cors = require('cors')
//Import the filter plug-in
const multer = require('multer')
//Use multer to generate a warehouse information
const storage =multer.diskStorage({
  destination:function(req,file,cb){
    //req, this request information
    //file, this request path
    //cb, callback function, use the callback function to set the storage path
    //The first parameter is null, indicating that the binary file should not be modified
    cb(null,'./uploads/'+file.fieldname)
  },
  filename:function(req,file,cb){
    //req, this request information
    //File, file information uploaded this time
    //cb, callback function, which sets the file name through the callback function
    console.log(file);
    //Take out the suffix from the file information and splice random numbers
    const tmp =path.extname(file.originalname)
    cb(null,`${file.fieldname}_${new Date().getTime()}-${Math.random().toString().slice(2)}${tmp}`)
  }   
})
// Configure receiver with warehouse information
const fileUpload = multer({storage})
const app = express()
//Mount cors to cross domain
app.use(cors())
//Configure on the required route
router.post('/upload',fileUpload.fields([
  {name:'pic'},
  {name:'photo'}
]),(req,res)=>{
  console.log('Receive request');
  console.log(req.files);
})
app.use(router)
app.listen(3000,()=>console.log('Port 3000'))

Posted by b-real on Wed, 17 Nov 2021 00:47:50 -0800