Browse Source

read and create

pull/1/head
遇见 4 years ago
parent
commit
e42be54ad6
  1. 1
      .gitignore
  2. 16
      YuJian-Blog-Admin/src/api/article.js
  3. 14
      YuJian-Blog-Admin/src/api/user.js
  4. 26
      YuJian-Blog-Admin/src/router/index.js
  5. 3
      YuJian-Blog-Admin/src/store/getters.js
  6. 4
      YuJian-Blog-Admin/src/store/index.js
  7. 38
      YuJian-Blog-Admin/src/store/modules/article.js
  8. 104
      YuJian-Blog-Admin/src/store/modules/user.js
  9. 2
      YuJian-Blog-Admin/src/utils/validate.js
  10. 42
      YuJian-Blog-Admin/src/views/Article/ArticleCreate.vue
  11. 50
      YuJian-Blog-Admin/src/views/Article/ArticleList.vue
  12. 3
      YuJian-Blog-Admin/src/views/dashboard/index.vue
  13. 4
      YuJian-Blog-Admin/vue.config.js
  14. 2
      YuJian-Blog-Server/Test.http
  15. 7
      YuJian-Blog-Server/db/config.js
  16. 59
      YuJian-Blog-Server/db/index.js
  17. 31
      YuJian-Blog-Server/router/article.js
  18. 4
      YuJian-Blog-Server/router/index.js
  19. 2
      YuJian-Blog-Server/router/jwt.js
  20. 7
      YuJian-Blog-Server/router/user.js
  21. 16
      YuJian-Blog-Server/service/article.js

1
.gitignore vendored

@ -1,7 +1,6 @@ @@ -1,7 +1,6 @@
.DS_Store
node_modules
/dist
db
# local env files
.env.local

16
YuJian-Blog-Admin/src/api/article.js

@ -0,0 +1,16 @@ @@ -0,0 +1,16 @@
import request from "@/utils/request";
export function getArticle() {
return request({
url: "/article/list",
method: "get"
});
}
export function AddArticle(data) {
return request({
url: "/article/create",
method: "post",
data
});
}

14
YuJian-Blog-Admin/src/api/user.js

@ -1,16 +1,16 @@ @@ -1,16 +1,16 @@
import request from '@/utils/request'
import request from "@/utils/request";
export function login(data) {
return request({
url: '/user/login',
method: 'post',
url: "/user/login",
method: "post",
data
})
});
}
export function getInfo(token) {
return request({
url: '/user/info',
method: 'get'
})
url: "/user/info",
method: "get"
});
}

26
YuJian-Blog-Admin/src/router/index.js

@ -3,33 +3,7 @@ import Router from 'vue-router' @@ -3,33 +3,7 @@ import Router from 'vue-router'
Vue.use(Router)
/* Layout */
import Layout from '@/layout'
/**
* Note: sub-menu only appear when route children.length >= 1
* Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
*
* hidden: true if set true, item will not show in the sidebar(default is false)
* alwaysShow: true if set true, will always show the root menu
* if not set alwaysShow, when item has more than one children route,
* it will becomes nested mode, otherwise not show the root menu
* redirect: noRedirect if set noRedirect will no redirect in the breadcrumb
* name:'router-name' the name is used by <keep-alive> (must set!!!)
* meta : {
roles: ['admin','editor'] control the page roles (you can set multiple roles)
title: 'title' the name show in sidebar and breadcrumb (recommend set)
icon: 'svg-name' the icon show in the sidebar
breadcrumb: false if set false, the item will hidden in breadcrumb(default is true)
activeMenu: '/example/list' if set path, the sidebar will highlight the path you set
}
*/
/**
* constantRoutes
* a base page that does not have permission requirements
* all roles can be accessed
*/
export const constantRoutes = [
{
path: '/login',

3
YuJian-Blog-Admin/src/store/getters.js

@ -3,6 +3,7 @@ const getters = { @@ -3,6 +3,7 @@ const getters = {
device: state => state.app.device,
token: state => state.user.token,
avatar: state => state.user.avatar,
name: state => state.user.name
name: state => state.user.name,
article: status => status.article.article
}
export default getters

4
YuJian-Blog-Admin/src/store/index.js

@ -4,6 +4,7 @@ import getters from './getters' @@ -4,6 +4,7 @@ import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import article from './modules/article'
Vue.use(Vuex)
@ -11,7 +12,8 @@ const store = new Vuex.Store({ @@ -11,7 +12,8 @@ const store = new Vuex.Store({
modules: {
app,
settings,
user
user,
article
},
getters
})

38
YuJian-Blog-Admin/src/store/modules/article.js

@ -0,0 +1,38 @@ @@ -0,0 +1,38 @@
import { getArticle } from "@/api/article";
const state = {
article: []
};
const mutations = {
SET_ARTICLE: (state, article) => {
state.article = article;
}
};
// get Article
const actions = {
getArticle({ commit }) {
return new Promise((resolve, reject) => {
getArticle()
.then(response => {
if (response.error) {
reject(response.errorMsg);
}
commit("SET_ARTICLE", response.data);
resolve(response.data);
})
.catch(error => {
reject(error);
});
});
}
};
module.exports = {
namespaced: true,
state,
mutations,
actions
};

104
YuJian-Blog-Admin/src/store/modules/user.js

@ -1,97 +1,101 @@ @@ -1,97 +1,101 @@
import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { login, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
const getDefaultState = () => {
return {
token: getToken(),
name: '',
avatar: ''
}
}
name: "",
avatar: "",
article: {}
};
};
const state = getDefaultState()
const state = getDefaultState();
const mutations = {
RESET_STATE: (state) => {
Object.assign(state, getDefaultState())
RESET_STATE: state => {
Object.assign(state, getDefaultState());
},
SET_TOKEN: (state, token) => {
state.token = token
state.token = token;
},
SET_NAME: (state, name) => {
state.name = name
state.name = name;
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
state.avatar = avatar;
}
}
};
const actions = {
// user login
login({ commit }, userInfo) {
const { username, password } = userInfo
const { username, password } = userInfo;
return new Promise((resolve, reject) => {
login({ username: username.trim(), password: password }).then(response => {
const { data } = response
commit('SET_TOKEN', data.token)
setToken(data.token)
resolve()
}).catch(error => {
reject(error)
})
})
login({ username: username.trim(), password: password })
.then(response => {
const { data } = response;
commit("SET_TOKEN", data.token);
setToken(data.token);
resolve();
})
.catch(error => {
reject(error);
});
});
},
// get user info
getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(response => {
const { data } = response
getInfo(state.token)
.then(response => {
const { data } = response;
if (!data) {
reject('Verification failed, please Login again.')
}
if (!data) {
reject("Verification failed, please Login again.");
}
const { name, avatar } = data
const { username, avatar } = data;
commit('SET_NAME', name)
commit('SET_AVATAR', avatar)
resolve(data)
}).catch(error => {
reject(error)
})
})
commit("SET_NAME", username);
commit("SET_AVATAR", avatar);
resolve(data);
})
.catch(error => {
reject(error);
});
});
},
// user logout
logout({ commit, state }) {
return new Promise((resolve, reject) => {
try {
removeToken()
resetRouter()
commit('RESET_STATE')
resolve()
removeToken();
resetRouter();
commit("RESET_STATE");
resolve();
} catch (e) {
reject(e)
reject(e);
}
})
});
},
// remove token
resetToken({ commit }) {
return new Promise(resolve => {
removeToken() // must remove token first
commit('RESET_STATE')
resolve()
})
removeToken(); // must remove token first
commit("RESET_STATE");
resolve();
});
}
}
};
export default {
namespaced: true,
state,
mutations,
actions
}
};

2
YuJian-Blog-Admin/src/utils/validate.js

@ -15,6 +15,6 @@ export function isExternal(path) { @@ -15,6 +15,6 @@ export function isExternal(path) {
* @returns {Boolean}
*/
export function validUsername(str) {
const valid_map = ['admin', 'editor']
const valid_map = ['YuJian', 'editor']
return valid_map.indexOf(str.trim()) >= 0
}

42
YuJian-Blog-Admin/src/views/Article/ArticleCreate.vue

@ -1,9 +1,45 @@ @@ -1,9 +1,45 @@
<template>
<div>ArticleCreate</div>
<div class="CreateFather">
<el-form @submit.native.prevent="createArticle" ref="form" :model="ArticleForm">
<el-form-item label="文章名称">
<el-input v-model="ArticleForm.title" class="ArticleTitleWidth"></el-input>
</el-form-item>
<el-form-item label="文章内容">
<el-input type="textarea" v-model="ArticleForm.content" style="width: 90%;"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" native-type="submit">立即创建</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { AddArticle } from "@/api/article";
export default {
name: 'ArticleCreate'
}
name: "ArticleCreate",
data() {
return {
ArticleForm: {
title: "",
content: "",
},
};
},
methods: {
createArticle() {
AddArticle(this.ArticleForm);
},
},
};
</script>
<style scoped>
.CreateFather {
margin: 30px 0px 0px 30px;
width: 100%;
}
.ArticleTitleWidth {
width: 500px;
}
</style>

50
YuJian-Blog-Admin/src/views/Article/ArticleList.vue

@ -1,9 +1,53 @@ @@ -1,9 +1,53 @@
<template>
<div>ArticleList</div>
<div class="ListFather">
<el-table
:data="ArticleData.filter(data => !search || data.title.toLowerCase().includes(search.toLowerCase()))"
style="width: 100%">
<el-table-column label="文章标题" prop="title"></el-table-column>
<el-table-column label="文章作者" prop="author"></el-table-column>
<el-table-column align="right">
<template slot="header" slot-scope="scope">
<el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
</template>
<template slot-scope="scope">
<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
name: 'ArticleList'
}
name: "ArticleList",
data() {
return {
ArticleData: [],
search: "",
};
},
computed: {
...mapGetters(["article"]),
},
methods: {
handleEdit(index, row) {
console.log(index, row);
},
handleDelete(index, row) {
console.log(index, row);
},
},
mounted() {
this.$store.dispatch("article/getArticle").then(() => {
this.ArticleData = this.article;
});
},
};
</script>
<style scoped>
</style>

3
YuJian-Blog-Admin/src/views/dashboard/index.vue

@ -1,6 +1,7 @@ @@ -1,6 +1,7 @@
<template>
<div class="dashboard-container">
<div class="dashboard-text">name: {{ name }}</div>
<div class="dashboard-text">Hello {{ name }}</div>
<div class="dashboard-text">这是一个很简单的基于Element-Admin的后台管理系统</div>
</div>
</template>

4
YuJian-Blog-Admin/vue.config.js

@ -27,13 +27,13 @@ module.exports = { @@ -27,13 +27,13 @@ module.exports = {
publicPath: '/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: process.env.NODE_ENV === 'development',
lintOnSave: false, //process.env.NODE_ENV === 'development',
productionSourceMap: false,
devServer: {
port: port,
overlay: {
warnings: false,
errors: true
errors: false
}
},
configureWebpack: {

2
YuJian-Blog-Server/Test.http

@ -1,6 +1,6 @@ @@ -1,6 +1,6 @@
@url = http://127.0.0.1:5000/
###
POST {{ url }}user/login
POST {{ url }}article/create
Content-Type: application/json
{

7
YuJian-Blog-Server/db/config.js

@ -0,0 +1,7 @@ @@ -0,0 +1,7 @@
module.exports = {
host: "host",
port: "port",
user: "user",
password: "password",
database: "database"
}

59
YuJian-Blog-Server/db/index.js

@ -0,0 +1,59 @@ @@ -0,0 +1,59 @@
const config = require("./config");
const mysql = require("mysql");
const { DebugMode } = require("../utils/constant");
const { resolve } = require("path");
const { rejects } = require("assert");
function connect() {
return mysql.createConnection({
host: config.host,
port: config.port,
user: config.user,
password: config.password,
database: config.database,
});
}
function querySql(sql) {
DebugMode && console.log("SQL", sql);
const conn = connect();
// 返回Promise对象
return new Promise((resolve, rejects) => {
// try&catch捕捉异常
try {
// 执行sql查询
conn.query(sql, (error, results) => {
if (error) {
rejects(error);
} else {
resolve(results);
}
});
} catch (e) {
rejects(e);
} finally {
conn.end();
}
});
}
function queryOne(sql) {
return new Promise((resolve, reject) => {
querySql(sql)
.then((results) => {
if (results && results.length > 0) {
resolve(results[0]);
} else {
resolve(null);
}
})
.catch((err) => {
reject(err);
});
});
}
module.exports = {
querySql,
queryOne,
};

31
YuJian-Blog-Server/router/article.js

@ -0,0 +1,31 @@ @@ -0,0 +1,31 @@
const express = require("express");
const { GetArticleList, AddArticle } = require("../service/article");
const Result = require("../models/Result");
const router = express.Router();
router.get("/list", async (req, res) => {
await GetArticleList().then((ArticleData) => {
if (ArticleData) {
new Result(ArticleData, "文章信息查询成功").success(res);
} else {
new Result("文章信息查询失败").fail(res);
}
});
});
router.post("/create", async (req, res) => {
if (req.body.title === "" || req.body.content === "") {
new Result("文章内容不能为空").fail(res);
} else {
await AddArticle(req.body.title, req.body.content).then((response) => {
if (response) {
new Result("文章插入成功").success(res);
} else {
new Result("文章插入失败").fail(res);
}
});
}
});
module.exports = router;

4
YuJian-Blog-Server/router/index.js

@ -4,16 +4,18 @@ const jwtAuth = require("./jwt"); @@ -4,16 +4,18 @@ const jwtAuth = require("./jwt");
const Result = require("../models/Result");
const userRouter = require("./user");
const ArticleRouter = require("./article");
const router = express.Router();
router.use(jwtAuth);
// router.use(jwtAuth);
router.get("/", (req, res) => {
res.send("Welcome Server");
});
router.use("/user", userRouter);
router.use("/article", ArticleRouter);
router.use((req, res, next) => {
next(boom.notFound("API不存在"));

2
YuJian-Blog-Server/router/jwt.js

@ -3,7 +3,7 @@ const { PRIVATE_KEY } = require("../utils/constant"); @@ -3,7 +3,7 @@ const { PRIVATE_KEY } = require("../utils/constant");
module.exports = jwt({
secret: PRIVATE_KEY,
// // 需要指定一个加密算法
// 需要指定一个加密算法
// algorithms: ['HS256'],
credentialsRequired: true,
}).unless({

7
YuJian-Blog-Server/router/user.js

@ -54,9 +54,10 @@ router.post( @@ -54,9 +54,10 @@ router.post(
router.get("/info", (req, res) => {
let decode = decoded(req);
console.log(decode);
findUser("admin").then((info) => {
console.log("admin", info);
const { username } = decode
console.log("decode", decode);
findUser(username).then((info) => {
console.log(username, info);
if (info) {
info.roles = [info.role];
new Result(info, "用户信息查询成功").success(res);

16
YuJian-Blog-Server/service/article.js

@ -0,0 +1,16 @@ @@ -0,0 +1,16 @@
const { querySql } = require("../db");
function GetArticleList() {
const sql = "SELECT * FROM admin_article";
return querySql(sql);
}
function AddArticle(title, content, author){
const sql = `INSERT INTO admin_article VALUES (NULL, '${title}', '${content}', 'YuJian', NULL);`
return querySql(sql);
}
module.exports = {
GetArticleList,
AddArticle
};
Loading…
Cancel
Save