This is the 28th day of my participation in Gwen Challenge

Counting up to today, plus this article, Node series has been updated more than ten articles, through these days of learning, Node is a beginner, write a few interfaces to their own is no problem, and then have a new understanding of session, cookie, I can use Node to verify and store cookies and sessions, and I have simply learned how to use Redis, as well as the operation of adding, deleting, modifying and deleting databases. Here, Node series is about to temporarily learn this, and I have written my own small blog has also used the interface I wrote. Today, the front desk page of the blog is also finished, and the data is successfully coordinated. The core code of the front and back end is explained next, and the recent learning is summarized a little ~

Post a few pictures first:

The above pictures are the login interface of blog, blog list, new blog, blog management, blog preview several interfaces, the basic function of blog is completed, but there are many deficiencies, now the knowledge reserve is not enough, can only wait for the later slowly updated ~

The Server side

app.js

All incoming routes are processed by app.js

/* * @Author: Tmier * @Date: 2021-06-07 22:52:26 * @LastEditTime: 2021-06-28 22:05:17 * @Description: * @LastModifiedBy: Tmier */
const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog.js')
const handleUserRouter = require('./src/router/user.js')
// Introduce utility function methods
const { get, set } = require('./src/db/redis')
// Get the cookie expiration time
const getCookieExpires = () = > {
  const d = new Date()
  d.setTime(d.getTime() + 24 * 60 * 60 * 1000)
  return d.toGMTString()
}
/ / the session data
// const SESSION_DATA = {}

// Used to process postData
const getPostData = req= > {
  return new Promise((resolve, reject) = > {
    if(req.method ! = ='POST') {
      resolve({})
      return
    }
    // Non-JSON data type, ignore and return {}
    if (req.headers['content-type'! = ='application/json']) {
      resolve({})
      return
    }
    / / correct
    let postData = ' '
    req.on('data'.chunk= > {
      postData += chunk.toString()
    })
    req.on('end'.() = > {
      if(! postData) { resolve({})return
      }
      // Successful return
      resolve(JSON.parse(postData))
    })
  })
}

const serverHandle = (req, res) = > {
  res.setHeader('Content-Type'.'application/json')

  / / get the path
  const url = req.url
  req.path = url.split('? ') [0]

  / / query
  req.query = querystring.parse(url.split('? ') [1])

  / / cookie
  req.cookie = {}
  const cookieStr = req.headers.cookie || ' '
  cookieStr.split('; ').forEach(item= > {
    if(! item) {return
    }
    console.log('item: ', item);
    const arr = item.split('=')
    const key = arr[0].trim()
    const val = arr[1].trim()
    req.cookie[key] = val
  })
  console.log('req.cookie', req.cookie);
  // Parse session using redis
  let needSetCookie = false // Whether to Set set-cookie. The default value is false
  let userId = req.cookie.userId // Get the userId in req
  console.log('userId', req.cookie.userId);
  // Handle the presence or absence of userId separately
  if(! userId) { needSetCookie =true // Enable Cookie setting on the server
    userId = `The ${Date.now()}_The ${Math.random()}` // Randomly generate the userId
    // Initialize the session value in redis
    set(userId, {})
  }
  / / get the session
  req.sessionId = userId / / set the req. SessionId
  get(req.sessionId)
    .then(sessionData= > {
      console.log('sessionData',sessionData);
      // debugger
      // Redis sessionData is null
      if (sessionData == null) {
        // Initialize the session value in redis
        set(req.sessionId, {})
        / / set the session
        req.session = {}
      } else {
        req.session = sessionData
      }
      / / postData processing
      return getPostData(req)
    })
    .then(postData= > {
      req.body = postData
      // Handle old blog routes

      // const blogData = handleBlogRouter(req, res)
      // if (blogData) {
      // res.end(JSON.stringify(blogData))
      // return
      // }

      // Handle blog routing
      const blogResult = handleBlogRouter(req, res)
      if (blogResult) {
        blogResult.then(blogData= > {
          // Set set-cookie when needSetCookie is true after routing
          if (needSetCookie) {
            res.setHeader('Set-Cookie'.`userId=${userId}; path=/; httponly; expires=${getCookieExpires()}`)
            needSetCookie = false
          }
          res.end(JSON.stringify(blogData))
        })
        return
      }

      // Process the user route
      // const userData = handleUserRouter(req, res)
      // if (userData) {
      // res.end(JSON.stringify(userData))
      // return
      // }
      const userResult = handleUserRouter(req, res)
      if (userResult) {
        userResult.then(userData= > {
          // Set set-cookie when needSetCookie is true after routing
          if (needSetCookie) {
            res.setHeader('Set-Cookie'.`userId=${userId}; path=/; httponly; expires=${getCookieExpires()}`)
            needSetCookie = false
          }
          res.end(JSON.stringify(userData))
        })
        return
      }

      // No route is matched, 404 is returned
      res.writeHead(404, { 'Content-Type': 'text/plain' })
      res.write('404 Not Found\n')
      res.end()
    })
}
module.exports = serverHandle

Copy the code

controller/blog.js

You only care about the data, you take it out of the database and you return it

/* * @Author: Tmier * @Date: 2021-06-08 23:18:55 * @LastEditTime: 2021-06-28 23:15:54 * @Description: * @LastModifiedBy: Tmier */

const {exec} = require('.. /db/mysql.js')

const getList = (author, keyword) = > {
  
  let sql = ` select * from blogs where 1=1 `
  if (author) {
    sql += `and author='${author}'`
  }
  if(keyword) {
    sql += `and title like '%${keyword}%' `
  }
  sql += `order by createtime desc; `
  // Return a Promise
  return exec(sql)
  
}
const getListEasy = (author, keyword) = > {
  
  let sql = ` select id, title, author from blogs where 1=1 `
  if (author) {
    sql += `and author='${author}'`
  }
  if(keyword) {
    sql += `and title like '%${keyword}%' `
  }
  sql += `order by createtime desc; `
  // Return a Promise
  return exec(sql)
  
}
// Blog details
const getDetail = id= > {
  const sql = `select * from blogs where id='${id}'`
  return exec(sql).then(rows= > {
    return rows[0]})}// Create a new blog
const newBlog = (blogData = {}) = > {
  const title = blogData.title
  const content = blogData.content
  const author = blogData.author
  const createTime = Date.now()
  const sql = `
    insert into blogs (title,content,createtime,author) values ('${title}', '${content}',${createTime}, '${author}');
  `
  return exec(sql).then(insertData= > {
    // console.log('insertData',insertData);
    return {
      id: insertData.insertId
    }
  })
}
const updateBlog = (id,blogData= {}) = > {
  const title= blogData.title
  const content = blogData.content
  const sql = `
    update blogs set title='${title}', content='${content}' where id=${id}; 
  `
  return exec(sql).then(updateData= > {
    // console.log('updateData', updateData);
    if(updateData.affectedRows > 0) {
      return true
    }
    return false})}const delBlog = (id,author) = > {
  const sql = `
    delete from blogs where id='${id}' and author='${author}';
  `
  return exec(sql).then(delData= > {
    if(delData.affectedRows > 0) {
      return true
    }
    return false})}module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
  getListEasy
}
Copy the code

controller/user.js

const {exec} = require('.. /db/mysql.js')
const login = (username, password) = > {
  const sql = `
    select username, realname from users where username='${username}' and password='${password}';
  `
  return exec(sql).then(rows= > {
    return rows[0) | | {}})}module.exports = {
  login
}
Copy the code

model/resModel.js

Unified model, the data model returned by the interface

/* * @Author: Tmier * @Date: 2021-06-08 07:19:55 * @LastEditTime: 2021-06-08 23:33:10 * @Description: * @LastModifiedBy: Tmier */
class BaseModel {
  constructor(data,message) {
    if(typeof data == 'string') {
      this.message = data
      data = null
      message = null
    }
    if(data) {
      this.data = data
    }
    if(message) {
      this.message = message
    }
  }
}

class SuccessModel extends BaseModel {
  constructor(data,message) {
    super(data, message)
    this.errno = 0}}class ErrorModel extends BaseModel {
  constructor(data,message) {
    super(data,message)
    this.errno = -1}}module.exports = {
  SuccessModel,
  ErrorModel
}
Copy the code

The front end

Front-end words, I do the page is relatively simple, in fact, there is no difficult point, simply stick it ~

utils/request.js

/* * @Author: Tmier * @Date: 2021-06-21 23:11:53 * @LastEditTime: 2021-06-28 21:43:22 * @Description: * @LastModifiedBy: Tmier */
import axios from 'axios'
import router from '@/router'
import {Message} from 'element-ui'
const request = axios.create({
  // baseURL: 'http://192.168.1.2:1996/', // configure the base path
  timeout: 1000 * 15.headers: {
    "Content-type": "application/json; charset=UTF-8",}})// Request interceptor
request.interceptors.request.use(
  request= > {
    return request
  },
  error= > {
    // If an error is reported, handle the error})// Response interceptor
request.interceptors.response.use(response= > {
  if(! response.data.errno ==0) {
    Message.error(response.data.message)
    if(response.data.errno == -1) {
      router.push({
        name: 'Login'}}})return response.data
}, error= > {})
export default request
Copy the code

filters/index.js

Time management for blogs

const dayjs = require('dayjs')
require('dayjs/locale/zh-cn') 
dayjs.locale('zh-cn') // global use
const relativeTime = require('dayjs/plugin/relativeTime')
dayjs.extend(relativeTime)
function transformTime(timestamp = +new Date(a)) {
  if (timestamp) {
    return dayjs(timestamp).fromNow()
  } else {
    return ' '}}export const Time = value= > {
  return transformTime(value)
}
Copy the code

Simple checking

  • Node’s processing of cookies and sessions is a bit confusing for me. I need to sort out the logic and figure out login authentication
  • I only learned the Node write interface, not the core API of Node
  • The next step is to put the small blog on the server and deploy it