使用nuxt,express,mysql,nginx创建个人博客系列-11
484
2020-01-24 18:37
10 个月前
保存文章类型
首先我们需要一个进到文章详情页面,然后通过提交按钮,修改或新增文章类型,判断是否是新增只需要传入id=0即可,下面我们首先添加路由
路由目录:server/admin/routers/categorys.js
//文章类型查看路由,根据id去渲染categorys_edit.html
router.get('/:id',async (req,res,next)=>{
let id = req.params['id'];
let name =""
//判断是否为0,不为0则需要去数据库查找出已经保存的内容
if(id){
let myConnect = await mysql.getConnect();
let sql = `select * from category where id = ${id}`;
let result = await mysql.query(myConnect,sql);
await mysql.release(myConnect);
if(result.length){
name = result[0]['name']
}
}
return res.render('categorys_edit', {
module_dir: config.admin.route,
id,
name
})
})
router.post('/edit',async (req,res,next)=>{
let {name,id} = req.body;
let userid = req.session.user.id
if(userid){
let myConnect = await mysql.getConnect();
let sql='';
let params = null;
if(id==0){
sql = `insert into category(user_id,name) values (?)`;
params = [userid,name];
}else{
sql = `UPDATE category SET name = '${name}' WHERE id = ${id}`;
}
let result = await mysql.query(myConnect,sql,params);
console.log(result)
await mysql.release(myConnect);
if(result.affectedRows === 1){
return res.send(util.resSuccess({
data:result
}))
}
return res.send(util.resError({
code:'user_id',
msg:"插入错误"
}))
}else{
return res.send(util.resError({
code:'user_id',
msg:"请登录"
}))
}
})
下面我们添加categorys_edit.html 目录:server/admin/views/categorys_edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<% include header.ejs%>
<title>categorys_edit</title>
</head>
<body>
<% include nav.ejs%>
<div class="container mt-3">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="row">
<div class="col-md-12 mb-3">
<label for="firstName">分类名称</label>
<input type="text" class="form-control" id="firstName" value="<%= name%>" placeholder="请输入分类名称">
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-md-12 mb-3">
<button type="button" name="" id="btn-submit" class="btn btn-dark btn-lg btn-block">提交</button>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
var module_dir = "<%= module_dir%>";
var id = "<%= id%>"
</script>
<script>
$(function(){
$('#btn-submit').on('click',function(){
var name = $('#firstName').val()
if(name){
$axios.post(`${module_dir}/categorys/edit`,{
name,
id
}).then(resp=>{
if(resp.status==1){
window.location=`${module_dir}/categorys` // 保存成功后跳转到类型列表页
}
})
}else{
alert('请输入分类名称')
}
})
})
</script>
</html>
你会看到这样的页面
上一篇-使用nuxt,express,mysql,nginx创建个人博客系列-10
下一篇-使用nuxt,express,mysql,nginx创建个人博客系列-12