留言板

1、初始化环境

koa2 test6

2、新建src文件夹,把下方四个文件放到src中


image.png

3、修改路径


image.png

4、规范目录与层级
image.png

5、安装mongoose

cnpm i mongoose --save

6、前端跨域允许带cookie的设置(在ajax.js中配置):

axios.defaults.withCredentials = true

服务端支持跨域的设置:
1、安装koa2-cors插件:

cnpm i koa2-cors --save

2、在app.js中配置:
先在上面引入

const cors = require('koa2-cors')

然后调用:
// 服务端支持跨域

app.use(cors({
origin: 'http://localhost:8080', // 支持前端哪个域可以跨域
credentials: true // 允许跨域的时候带着 cookie
}))

【origin:"" 支持前端所有的域可以跨域,前提是不要求跨域带cookie。也就是说服务端不要求跨域带cookie,origin的值可以是""。但是我们这里允许跨域的时候带着 cookie,那么origin的值就必须是一个具体的前端的域】
7、实现注册功能
1)定义路由

const router = require('koa-router')()
const { register } = require("../controller/user")

router.prefix('/users')
// 注册
router.post("/register", async (ctx, next) => {
  const userInfo = ctx.request.body
  // 提交注册
  try {
    const newUser = await register(userInfo);
    ctx.body = {
      errno: 0,
      data: newUser
    }
  } catch (ex) {
    console.error("注册失败", ex)
    ctx.body = {
      errno: -1,
      message: "注册失败"
    }
  }
})

module.exports = router

2)controller/user.js文件

const User = require("../model/User")
// 注册
async function register(userInfo = {}) {
    // 插入数据库
    const newUser = await User.create(userInfo)
    return newUser
}
module.exports = {
    register
}

8、实现登录验证
定义路由

const { register ,login} = require("../controller/user")
// 登录
router.post('/login', async (ctx, next) => {
  console.log(121212)
  // 获取登录信息
  const { username, password } = ctx.request.body
  // 验证登录
  const res = await login(username, password)
  if (res) {
    // 登陆成功
    // 设置 session
    ctx.session.userInfo = {
      username
    }

    // 返回
    ctx.body = {
      errno: 0
    }
  } else {
    // 登录失败
    ctx.body = {
      errno: -1,
      message: '登录验证失败'
    }
  }
})

user.js

// 登录
async function login(username, password) {
    // 从数据库查询用户,是否存在
    const user = await User.findOne({ username, password })
    if (user != null) {
        // 登录成功
        return true
    }
    // 登录失败
    return false
}

module.exports = {
    register,
    login
}

设置session的前提,先安装插件

 cnpm i koa2-cors --save

在app.js引入和配置

const session = require('koa-generic-session')
// 配置 session
app.keys = ['dssUII^*(*123123']
app.use(session({
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000 // 一天
  }
}))

登录验证的中间件

// 登录验证的中间件

async function loginCheck(ctx, next) {
    const session = ctx.session || {}
    const userInfo = session.userInfo
    if (userInfo && userInfo.username) {
        // 登录验证通过
        await next()
        return
    }
    // 登录验证失败
    ctx.body = {
        errno: -1,
        message: '用户尚未登录'
    }
}

module.exports = loginCheck

9、创建留言
1)新建文件(comment.js),定义路由

const router = require('koa-router')()
const loginCheck = require('../middleware/loginCheck')
const { create } = require('../controller/comment')

router.prefix('/comment')

// 创建留言
router.post('/create', loginCheck, async (ctx, next) => {
   // 获取留言信息
   const { content } = ctx.request.body
   const { username } = ctx.session.userInfo

   try {
       // 提交留言(controller)
       const newComment = await create(content, username)

       // 返回
       ctx.body = {
           errno: 0,
           data: newComment
       }
   } catch (ex) {
       console.error('创建留言失败', ex)
       ctx.body = {
           errno: -1,
           message: '创建留言失败'
       }
   }
})

module.exports = router

2)在app.js中引入和配置

const comment = require('./routes/comment')
app.use(comment.routes(), comment.allowedMethods())

3)存放到数据库中(controller/comment.js)


// 留言 controller

const Comment = require('../model/Comment')

// 创建留言
async function create(content, username) {
    // 保存到数据库
    const newComment = await Comment.create({
        content,
        username
    })
    return newComment
}

module.exports = {
    create
}

10、获取留言列表

// 获取留言列表
router.get('/list', loginCheck, async (ctx, next) => {
    // 获取 filterType:1 - 全部;2 - 自己
    let { filterType } = ctx.query
    filterType = parseInt(filterType) || 1

    // 获取当前用户名
    let username = ''
    if (filterType === 2) {
        username = ctx.session.userInfo.username
    }

    // 获取留言列表
    const list = await getList(username)
    ctx.body = {
        errno: 0,
        data: list
    }
})

controller/comment.js

// 获取留言列表
async function getList(username = '') {
    const whereOpt = {}
    if (username) {
        whereOpt.username = username
    }

    const list = await Comment.find(whereOpt).sort({ _id: -1 })
    return list
}

11、删除留言

// 删除留言
router.post('/del', loginCheck, async (ctx, next) => {
    // 获取 id
    const { _id } = ctx.request.body
    // 获取用户名
    const { username } = ctx.session.userInfo
    // 执行删除
    try {
        await del(_id, username)
        ctx.body = {
            errno: 0
        }
    } catch (ex) {
        // 失败
        console.error('删除失败', ex)
        ctx.body = {
            errno: -1,
            message: '删除失败'
        }
    }
})

controller/comment.js

// 删除留言
async function del(_id, username) {
    await Comment.remove({
        _id,
        username // 只能删除自己的留言
    })
}

11、更新留言

// 更新留言
router.post('/update', loginCheck, async (ctx, next) => {
    // 获取 id content
    const { _id, content } = ctx.request.body
    // 获取用户名
    const { username } = ctx.session.userInfo
    // 执行更新
    try {
        const newData = await update(_id, username, content)
        ctx.body = {
            errno: 0,
            data: newData
        }
    } catch (ex) {
        // 失败
        console.error('更新失败', ex)
        ctx.body = {
            errno: -1,
            message: '更新失败'
        }
    }
})

controller/comment.js

// 更新留言
async function update(_id, username, content) {
    const newData = await Comment.findOneAndUpdate(
        { _id, username }, // 只能跟新自己的留言
        { content },
        { new: true } // 返回更新之后的最新留言
    )
    return newData
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。