Node.js 从零开发 web server博客项目[数据存储]

web server博客项目

  1. Node.js 从零开发 web server博客项目[项目介绍]
  2. Node.js 从零开发 web server博客项目[接口]
  3. Node.js 从零开发 web server博客项目[数据存储]
  4. Node.js 从零开发 web server博客项目[登录]
  5. Node.js 从零开发 web server博客项目[日志]
  6. Node.js 从零开发 web server博客项目[安全]
  7. Node.js 从零开发 web server博客项目[express重构博客项目]
  8. Node.js 从零开发 web server博客项目[koa2重构博客项目]
  9. Node.js 从零开发 web server博客项目[上线与配置]

nodejs链接 mysql 封装成工具

  • 安装MySQL

cnpm i mysql -S

  • 创建src/conf/db.js

const env = process.env.NODE_ENV // 环境参数

// 配置
let MYSQL_CONF

if (env === 'dev') {
  MYSQL_CONF = {
    host: 'localhost',
    user: 'root',
    password: 'root',
    port: '3306',
    database: 'myblog'
  }
}

if (env === 'production') {
  MYSQL_CONF = {
    host: 'localhost',
    user: 'root',
    password: 'root',
    port: '3306',
    database: 'myblog'
  }
}

module.exports = { MYSQL_CONF }
  • 创建scr/db/mysql.js
const mysql = require('mysql')
const { MYSQL_CONF } = require('../conf/db')

// 创建链接对象
var con = mysql.createConnection(MYSQL_CONF);

// 开始链接
con.connect();

// 统一执行 sql 的函数
function exec(sql) {
  const promise = new Promise((resolve, reject) => {
    con.query(sql, function (error, result) {
      if (error) {
        reject(error)
        return
      }
      resolve(result)
    })
  })
  return promise
}

module.exports = {
  exec
}

API对接MySQL (博客列表)

controller/blog.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 exec(sql)
  // [{
  //   id: 1,
  //   title: '标题a',
  //   content: '内容a',
  //   createTime: 1562085127324,
  //   suthor: 'zhangsan'
  // }]
}

router/blog.js

// 获取博客列表
  if (method === 'GET' && path === '/api/blog/list') {
    const {
      author,
      keyword
    } = req.query || ''
    // const listData = getList(author, keyword)
    // return new SuccessModel(listData)
    const result = getList(author, keyword)
    return result.then(listData => {
      return new SuccessModel(listData)
    })
  }

app.js

getPostData(req).then(postData => {
  req.body = postData

  // 处理 blog 路由
  // const blogData = handleBlogRouter(req, res)
  // if (blogData) {
  //   res.end(
  //     JSON.stringify(blogData)
  //   )
  //   return
  // }
  const blogResult = handleBlogRouter(req, res)
  if (blogResult) {
    blogResult.then(blogData => {
      res.end(
        JSON.stringify(blogData)
      )
    })
    return
  }
  ...
  // 未命中路由, 返回404
  res.writeHead(404, {
    "content-type": "text/plain"
  })
  res.write("404 Not Found\n")
  res.end()

})

在这里插入图片描述

API对接MySQL (博客详情和新建)

controller/blog.js

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

// 博客内容
const getDtail = (id) => {
  // return {
  //   id: 1,
  //   title: '标题a',
  //   content: '内容a',
  //   createTime: 1562085127324,
  //   suthor: 'zhangsan'
  // }

  let sql = `select * from blogs where id='${id}'`
  return exec(sql).then(rows => {
    return rows[0]
  })
}

// 新增一篇博客
const newBlog = (blogData) => {
  // 赋予id
  // return {
  //   id: 3
  // }
  const {title, content, author} = blogData
  const createtime = Date.now()
  
  let sql = `insert into blogs (title, content, createtime, author) values ('${title}', '${content}', '${createtime}', '${author}');`
  return exec(sql)
}

router/blog.js

  // 获取一篇博客的内容
  if (method === 'GET' && path === '/api/blog/detail') {
    // const data = getDtail(id)
    // return new SuccessModel(data)

    const result = getDtail(id)
    return result.then(data => {
      return new SuccessModel(data)
    })
  }

  // 新增一篇博客
  if (method === 'POST' && path === '/api/blog/new') {
    // const data = newBlog(req.body)
    // return new SuccessModel(data)
    
    req.body.author = 'zhangsan' // 假数据, 待开发登陆时再改成真实数据
    
    const result = newBlog(req.body)
    return result.then(data => {
      return new SuccessModel(data)
    })
  }

在这里插入图片描述
在这里插入图片描述

API对接MySQL (更新和删除)

更新

// 更新一篇博客
const updateBlog = (id, blogData = {}) => {
  // console.log(`更新一篇博客, ID:${id}, 内容:${blogData}`)
  // return true

  const {title, content} = blogData

  const sql = `update blogs set title='${title}', content='${content}' where id=${id}`
  return exec(sql).then(updateData => {
    console.log('updateData is ', updateData);
    if (updateData.affectedRows > 0) {
      return true
    }
    return false
  })
}

*********************
  // 更新一篇博客
  if (method === 'POST' && path === '/api/blog/update') {
    const result = updateBlog(id, req.body)
    // if (result) {
    //   return new SuccessModel(data)
    // } else {
    //   return ErrorModel('更新博客失败')
    // }

    return result.then(val => {
      if (val) {
        return new SuccessModel()
      } else {
        return ErrorModel('更新博客失败')
      }
    })
  }

在这里插入图片描述

删除

// 删除一篇博客
const delBlog = (id, author) => {
  // console.log(`删除一篇博客, ID:${id}`)
  // return true

  const sql = `delete from blogs where id='${id}' and author='${author}'`
  return exec(sql).then(delData => {
    if (delData.affectedRows > 0) {
      return true
    }
    return false
  })
}

*********************
  // 删除一篇博客
  if (method === 'POST' && path === '/api/blog/del') {
    // const result = delBlog(id)
    // if (result) {
    //   return new SuccessModel(result)
    // } else {
    //   return new ErrorModel('删除博客失败')
    // }

    const author = 'zhangsan'
    const result = delBlog(id, author)
    return result.then(val => {
      if (val) {
        return new SuccessModel(result)
      } else {
        return new ErrorModel('删除博客失败')
      }
    })
  }

API对接MySQL (登录)

controller/user.js

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

const loginCheck = (username, password) => {
  // if (username === 'zhangsan' && password === '1234') {
  //   return true
  // }
  const sql = `select username, realname from users where username='${username}' and password='${password}'`
  return exec(sql).then(rows => {
    return rows[0] || {}
  })
}

module.exports = {
  loginCheck
}

router/user.js

const {
  loginCheck
} = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')

const handleUserRouter = (req, res) => {
  const {
    method,
    path
  } = req

  // 登录
  if (method === 'POST' && path === '/api/user/login') {
    const {
      username,
      password
    } = req.body
    const result = loginCheck(username, password)

    // if (result) {
    //   return new SuccessModel(result)
    // } else {
    //   return new ErrorModel('登录失败')
    // }

    return result.then(data => {
      if (data.username) {
        return new SuccessModel()
      }
      return new ErrorModel('登录失败')
    })
  }
}

module.exports = handleUserRouter

app.js

// 处理 user 路由
    // const userData = handleUserRouter(req, res)
    // if (userData) {
    //   res.end(
    //     JSON.stringify(userData)
    //   )
    //   return
    // }

    const userResult = handleUserRouter(req, res)
    if (userResult) {
      userResult.then(userData => {
        res.end(
          JSON.stringify(userData)
        )
      })
      return
    }
    ```
posted @ 2019-07-22 02:19  仲灏  阅读(7249)  评论(0编辑  收藏  举报