Node — handle an increase in upload operations and rendering pages

Time:2020-3-24

The end of a period of study

I don’t know what I’m writing. I just think I’ve learned something and just want to record it
Just a moment, so that I can know that I have learned this field, and I need to motivate myself more^^O(∩(O) ha ha.
The following content does not match the title completely, but the following content synthesizes the application of the previous several articles and adds
Some things

JS code with HTML code

import express from 'express'
import Advert from '../models/advert'
import formidable from 'formidable'
import config from '../config'
import { basename } from 'path'

//Create a routing container and mount all routing middleware to the routing container
const router = express.Router()

router.get('/advert', (req, res, next) => {
  const page = Number.parseInt(req.query.page, 10)
  const pageSize = 5
  Advert
    .find()
    .skip((page - 1) * pageSize)
    .limit(pageSize)
    .exec((err, adverts) => {
      if (err) {
        return next(err)
      }
      Advert.count((err, count) => {
        if (err) {
          return next(err)
        }
        Const totalpage = math.ceil (count / PageSize) // total page number = total records / display size of each page
        res.render('advert_list.html', {
          adverts,
          totalPage,
          page
        })
      })
    })
})

router.get('https://www.cnblogs.com/advert/add', (req, res, next) => {
  res.render('advert_add.html')
})

/**
 * POST https://www.cnblogs.com/advert/add
 * body: { title, image, link, start_time, end_time }
 */
router.post('https://www.cnblogs.com/advert/add', (req, res, next) => {
  const form = new formidable.IncomingForm()
  Form. Uploaddir = config. Uploaddir // configure the upload and receive path of the formidable file
  Form. Keepextensions = true // configure to keep the original extension of the file
  form.parse(req, (err, fields, files) => {
    if (err) {
      return next(err)
    }

    Const body = fields // common form fields
    Body. Image = basename (files. Image. Path) // here parse and extract the uploaded file name and save it to the database

    const advert = new Advert({
      title: body.title,
      image: body.image,
      link: body.link,
      start_time: body.start_time,
      end_time: body.end_time,
    })

    advert.save((err, result) => {
      if (err) {
        return next(err)
      }
      res.json({
        err_code: 0
      })
    })
  })
})

router.get('/advert/list', (req, res, next) => {
  Advert.find((err, docs) => {
    if (err) {
      return next(err)
    }
    res.json({
      err_code: 0,
      result: docs
    })
  })
})

/// advert / one /: advertid is a fuzzy matching path
//It can match the path form of / advert / one / *
//For example, / advert / one / 1 / advert / one / 2 / advert / one / A / advert / one / ABC
//But / advert / one or / advert / one / A / B is not good
//As for the name of advertid, you can get it through req.params in the processing function
router.get('/advert/one/:advertId', (req, res, next) => {
  Advert.findById(req.params.advertId, (err, result) => {
    if (err) {
      return next(err)
    }
    res.json({
      err_code: 0,
      result: result
    })
  })
})

// /advert/edit
router.post('/advert/edit', (req, res, next) => {
  Advert.findById(req.body.id, (err, advert) => {
    if (err) {
      return next(err)
    }
    const body = req.body
    advert.title = body.title
    advert.image = body.image
    advert.link = body.link
    advert.start_time = body.start_time
    advert.end_time = body.end_time
    advert.last_modified = Date.now()

    //Because the save here has an internal ID, no new data will be added here, but the existing data will be updated
    advert.save((err, result) => {
      if (err) {
        return next(err)
      }
      res.json({
        err_code: 0
      })
    })
  })
})

router.get('/advert/remove/:advertId', (req, res, next) => {
  Advert.remove({ _id: req.params.advertId }, err => {
    if (err) {
      return next(err)
    }
    res.json({
      err_code: 0
    })
  })
})

export default router
{% extends "layout.html" %} {% block body %}

  
    
    
      Advertising management
      Add ads
    
    
      
        
          Title
          
            
          
        
        
          picture
          
            
          
        
        
          link
          
            
          
        
        
          start time
          
            
          
        
        
          End time
          
            
          
        
        
          
            
          
        
      
    
  

{% endblock %}

{% block script %}




// XMLHTTPRequest 1
// XMLHTTPRequest 2
$('form').on('submit', function (e) {
  // var formData = new FormData()
  // formData.append('name', 'Jack')
  // formData.append('age', '18')
  // formData.append('file', document.getElementById('file').files[0])

  // var xhr = new XMLHttpRequest()
  // xhr.open('post', 'https://www.cnblogs.com/advert/add')
  // xhr.send(formData)
  // return false
  $.ajax({
    url: $(this).attr('action'),
    type: $(this).attr('method'),
    data: new FormData($(this)[0]),
    //When your data option is submitted as a formdata object, be sure to configure processdata as false
    //Otherwise, the asynchronous submission of jQuery will not take effect
    processData: false,  // tell jQuery not to process the data
    //When submitting a formdata object, remember to set the contenttype to false
    //Otherwise, jQuery will default content type to application / x-www-form-urlencoded; charset = UTF-8
    contentType: false,  // tell jQuery not to set contentType
    success: function (data) {
      if (data.err_code === 0) {
        window.location.href = '/advert'
      }
    }
  })
  return false
})

{% endblock %}
{% extends "layout.html" %} 

{% block body %}

  
    
    
      Advertising management
      Advertising list
    
    
      Add ads
    
    
      
        
          
            in years
          
          
            By gender
          
          
            By Region
          
          
            By date
          
          screen
        
      
      
        
          
            Serial number
            Title
            picture
            link
            start time
            End time
            Clicks
            operation
          
        
        
          {% for item in adverts %}
          
            0
            {{ item.title }}
            
              
            
            {{ item.link }}
            {{ item.start_time }}
            {{ item.end_time }}
            1
            
              edit
              delete
            
          
          {% endfor %}
        
      
    
    
    
      Previous page
      {% for i in range(0, totalPage) -%}
        {% if (i + 1) === page %}
         {{ i + 1 }}
        {% else %}
          {{ i + 1 }}
        {% endif %}
      {%- endfor %}
      next page
    
  

{% endblock %} {% block script %} {% endblock %}

Recommended Today

A general solution to the failure of ruby to install gem package

Ruby language upgrade is more diligent. However, a large number of versions make the compatibility of libraries a big problem. Some gems explicitly do not support a particular version of ruby, while others are not compatible with a higher version. Plus, gem has its own version. It’s a mess. Even if you use Ruby version […]