目录
效果图:
客户端
views/userManage/index.vue
views/userManage/userManageDialog
utils/alioss.js
utils/index.js
utils/request.js
router.js
main.js
vue.config.js
服务端
models/User.js
routes/user.js
db.js
app.js
gitee地址:https://gitee.com/LiDaJiang/git_vue2_koa2_mongoose_zsgc_alioss/tree/master
搜索
重置
新增
刷新
编辑
删除
const OSS = require("ali-oss");
let client = new OSS({
region: "oss-cn-chengdu",//这里改成自己的
accessKeyId: "xxx",//这里改成自己的
accessKeySecret: "xxx",//这里改成自己的
bucket: "bucket-lijiang-test",//这里改成自己的
});
export default client;
//通过img和video的url组成的数组来删除服务器中的img,video
export async function deleteUrls(arr_deleteUrl = [], client_alioss = {}) {
if (arr_deleteUrl.length == 0) {
return
}
let arr_pathname = [];
for (const item of arr_deleteUrl) {
let { pathname } = new URL(item);//new URL()解决大图片加载失败问题。因为大图片的url中含有uploadid,导致url不能直接预览
//decodeURIComponent函数解决中文乱码
arr_pathname.push(decodeURIComponent(pathname));
}
if (arr_pathname.length !== 0) {
await client_alioss.deleteMulti(arr_pathname);
}
}
// 两个数组取差集,返回arrA中有,而arrB中没有的。
// 如arrA = ["a", "b", "c", "d"];arrB = ["a", "b", "e"];则返回["c","d"]
export function arrayDifference(arrA, arrB) {
return arrA.filter(item => !arrB.includes(item))
}
import axios from 'axios'
const service = axios.create({
timeout: 5000
})
service.interceptors.request.use(
config => {
return config
},
error => {
return Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
return response
},
error => {
return Promise.reject(error)
}
)
export default service
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [{
path: '/',
name: 'home',
component: () => import("@/views/home.vue"),
redirect: "/userManage",
children: [{
path: '/userManage',
name: 'userManage',
component: () => import("@/views/userManage/index")
}]
}]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
module.exports = {
lintOnSave: false, //取消eslint
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000', //设置开发环境服务域名和端口号 别忘了加http
changeOrigin: true, //這裡true表示实现跨域
pathRewrite: {
'^/api': ''//使用时,如:axios.get('/api/login')
}
}
}
}
}
const mongoose = require('../db.js')
let UserSchema = mongoose.Schema({
// 用户名
username: {
type: String,
required: true,
unique: true
},
// 密码
password: String,
//图片地址
imgurl: {
type: Array,
default: () => []
},
date: {
type: Date,
default: Date.now
}
})
// 创建模型对象
// 第二个对象指定约束对象实例,第三个对象指定数据库中的表名。有了第三个参数后,第一个参数随便写
module.exports = mongoose.model('User', UserSchema, "user")
const router = require('koa-router')()
const User = require("../models/User"); //引入模块模型
router.prefix('/userManage')
//获取用户列表
router.get('/list', async (ctx, next) => {
let data = await User.find({})
ctx.body = {
code: 200,
message: "请求成功",
data,
}
})
//新增用户
router.post('/add', async (ctx, next) => {
let { username, password, imgurl } = ctx.request.body;
await User.create({ username, password, imgurl })
ctx.body = { code: 200, message: "新增成功" }
})
//编辑用户
router.post('/edit/:_id', async (ctx, next) => {
let { username, password, imgurl } = ctx.request.body;
let { _id } = ctx.params
await User.findByIdAndUpdate(_id, { username, password, imgurl })
ctx.body = { code: 200, message: "编辑成功" }
})
//删除用户
router.get('/delete/:_id', async (ctx, next) => {
let { _id } = ctx.params;
let { imgurl } = await User.findByIdAndDelete(_id)
ctx.body = { code: 200, message: "删除成功", imgurl }
})
//根据关键字查询用户。模糊查询
router.post('/search', async (ctx, next) => {
let { searchName } = ctx.request.body;
let data = await User.find({ username: { $regex: searchName } })
ctx.body = { code: 200, message: "查询成功", data }
})
module.exports = router
//db.js
let mongoose = require('mongoose')
mongoose.set('useCreateIndex', true)
mongoose.set('useNewUrlParser', true)
mongoose.set('useUnifiedTopology', true)
const DB_NAME = 'test_alioss' //数据库名,自己更换
const DB_URL = 'localhost:27017'
mongoose.connect(`mongodb://${DB_URL}/${DB_NAME}`)
mongoose.connection.on('open', err => {
if (err) {
console.log(err)
return
}
console.log("数据库连接成功!")
})
module.exports = mongoose;
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const users = require('./routes/users')
const user = require('./routes/user')
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
extension: 'ejs'
}))
// logger
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(user.routes(), user.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
module.exports = app