1.创建管理员
1.1 文件上传处理
- express 本身是获取不到文件上传的数据,所以需要一个中间件来专门处理中间件 multer
multer({dest: './uploadImages'})
表示将上传的图片传输到指定文件夹(这里以uploadImages为例,如果没有该文件夹,会自动生成),如果不添加dest属性,这些文件将保存在内存中,永远不会写入磁盘
const multer = require('multer')
const path = require('path')
const uploadPath = path.join(__dirname, '../../uploads')
const upload = multer({ dest: uploadPath })
app.post('/admin/api/upload', upload.single('file'), (req, res) => {
const file = req.file
console.log(uploadPath);
file.url = `http://localhost:3000/uploads/${file.filename}`
res.send(file)
})
1.2 数据库存密码处理,不能明文保存,使用散列存储bcryptjs
const mongoose = require('mongoose')
const admin = mongoose.Schema({
username:{type:String},
password:{
type:String,
select:false,
set(value) {
return require('bcryptjs').hashSync(value,12)
}
}
})
const AdminUser = mongoose.model('AdminUser',admin)
module.exports = AdminUser
1.3 登录接口处理
- 当用户登录时,校验登录名和密码,然后返回一个token
const jwt = require('jsonwebtoken')
const assert = require('http-assert')
const AdminUser = require('../../models/AdminUser')
app.post('/admin/api/login',async (req,res)=>{
const { username , password } = req.body
const user = await AdminUser.findOne({username}).select('+password')
assert(user,422,'用户不存在')
const isValid = require('bcryptjs').compareSync(password,user.password)
assert(isValid,422,'密码错误')
const token = jwt.sign({id:user._id},app.get('secret'))
res.send({token})
})
1.4 客户端进行路由限制
{path: '/login',component: Login,meta:{isPublic:true}}
router.beforeEach((to,from,next)=>{
console.log(to.meta)
if(!to.meta.isPublic && !localStorage.getItem('token')){
return next('/login')
}
next()
})
1.5 上传文件的登录校验
const auth = {
methods:{
getAuthHeaders(){
return {Authorization:`Bear ${localStorage.getItem('token') || ''}`}
}
}
}
export default auth
<el-upload
class="avatar-uploader"
:action="$http.defaults.baseURL + '/uploads'"
:show-file-list="false"
:headers="getAuthHeaders()"
:on-success="handleAvatarSuccess">
<img v-if="model.avatar" :src="model.avatar" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
- 因为编辑和新建都在同一个界面,所以在
需要添加一个key
,这里使用
2.新建文章
- 编辑文章内容时使用了富文本编辑器
vue-quil-editor
2.1 安装vue-quill-editor
npm install vue-quill-editor -save
2.2 安装vue-quill-editor
npm install quill -S
2.3 导入
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import {quillRedefine} from 'vue-quill-editor-upload'
2.4 使用(包含文件上传)
<template>
<quill-editor style="height:400px;" v-model="model.detail" :options="editorOption"/>
</template>
<script>
components:{
quillEditor
},
created(){
this.editorOption = quillRedefine(
{
uploadConfig: {
action: this.$http.defaults.baseURL + '/uploads',
name: 'file',
methods: 'POST',
res: response => {
return response.url
}
},
theme:'snow'
}
)
}
</script>
3.新建评论
3.1 建立 schema 和 model
const monoogse = require('mongoose')
const Category = require('../models/Category')
const AdminUser = require('../models/AdminUser')
const Comment = require('../models/Comment')
const articleSchema = monoogse.Schema({
categories:[{
type:monoogse.SchemaTypes.ObjectId,
ref:Category
}],
title:{
type:String,
require:true
},
image:{
type:String,
require:true
},
account:{
type:String
},
date:{
type:String
},
authorinfo:{
type:monoogse.SchemaTypes.ObjectId,
ref:AdminUser
},
detail:{
type:String,
require:true
},
comments:[{
type:monoogse.SchemaTypes.ObjectId,
ref:'Comment'
}]
})
const Article = monoogse.model('Article',articleSchema)
module.exports = Article
3.1 获取文章列表
let pageSize = parseInt(req.query.size) || 5;
let currentPage = parseInt(req.query.page) || 1;
queryOptions.limit = pageSize
queryOptions.skip = (currentPage - 1) * pageSize
const model = await req.Model.find().setOptions(queryOptions).populate({
path:'authorinfo categories comments',
populate:{
path:'user'
}
})
const all = await req.Model.find()
const total = all.length
res.send({total,list:model})
- 查询的数据如下: