P32:后台管理系统开发11-实现添加文章的方法

目录
文章目录隐藏
  1. 选择类别后调用方法
  2. 对发布时间文本框修改
  3. 再对文章标题文本框进行修改
  4. 编写文章保存方法
  5. 编写中台的 addArticle 接口
  6. 编写对应的路由
  7. 配置 apiUrl.js 文件
  8. 编写 saveArticle 方法
  9. 编写中台接口方法
  10. 后台 apiUrl.js 的配置
  11. 后台保存方法的修改

本文主要内容是把文章中的内容添加到数据库中,内容虽然比较多,但是很多知识我们已经熟悉,都是利用 axios 对数据库进行操作。

选择类别后调用方法

现在选择文章类别后,前台还没办法根据选择的内容进行改变,这是我们使用了 React Hooks 的后遗症,必须使用对应 set 方法才可以改变 state 的值。

先编写selectTypeHangdler方法,代码如下:

//选择类别后的便哈
const selectTypeHandler = (value) = >{
    setSelectType(value)
}

然后再<Select>组件上的onChange事件上进行调用,代码如下:

<Select defaultValue={selectedType} size="large" onChange={selectTypeHandler}>
    {
        typeInfo.map((item,index)=>{
            return (<Option key={index} value={item.Id}>{item.typeName}</Option>)
        })
    }
</Select>

然后进行调试修改,对selectedType初始值进行初始化设置。

对发布时间文本框修改

选择文章可用后,修改发布日期对应的文本框,增加相应方法,让选择日期文本框也变的可用,代码如下:

<Col span={12}>
    <div className="date-select">
        <DatePicker
            onChange={(date,dateString)=>setShowDate(dateString)} 
            placeholder="发布日期"
            size="large"
        />
        </div>
</Col>

再对文章标题文本框进行修改

标题对应的文本框也要进行对相应的操作,代码如下:

<Col span={16}>
    <Input 
            value={articleTitle}
            placeholder="博客标题" 
            onChange={e=>{setArticleTitle(e.target.value)}}
            size="large" />
</Col>

编写文章保存方法

这些基本的操作都完成后,我们可以编写文章的保存方法,这里我先只作为空的验证,先不向数据库里插入数据,之后在编写玩中台接口后,我们再进行插入。

const saveArticle = () => {
    if(!selectedType){
        message.error('必须选择文章类型!');
        return false;
    } else if (!articleTitle) {
        message.error('文章名称不能为空!');
        return false;
    } else if (!articleContent) {
        message.error('文章内容不能为空!');
        return false;
    } else if (!introducemd) {
        message.error('文章简介不能为空!');
        return false;
    } else if (!showDate) {
        message.error('发布日期不能为空!');
        return false;
    }
    message.success('检验通过!');
}

然后在保存按钮的部分添加上 onClick 事件,代码如下:

<Col span={24}>
    <Button  size="large">暂存文章</Button>&nbsp;
    <Button type="primary" size="large" onClick={saveArticle}>发布文章</Button>
    <br/>
</Col>

然后就可以点击预览了,看看是否可以操作,进行调试。

文章保存

然后我们继续完善中台接口和后台的saveArticle方法。

编写中台的 addArticle 接口

service文件夹下面的/app/controller/admin/main.js文件里,新编写一个添加文章的方法addArticle()。代码如下:

//添加文章
async addArticle(){
    let tmpArticle= this.ctx.request.body
    const result = await this.app.mysql.insert('article',tmpArticle)
    const insertSuccess = result.affectedRows === 1
    const insertId = result.insertId

    this.ctx.body={
        isScuccess:insertSuccess,
        insertId:insertId
    }
}

编写对应的路由

方法写完了还需要配置路由,才能让后台管理系统访问,所以这里添加需要到/app/router/admin.js里进行配置,代码如下:

module.exports = app =>{
    const {router,controller} = app
    const adminauth = app.middleware.adminauth()
    router.get('/admin/index',controller.admin.main.index)
    router.get('/admin/getTypeInfo',adminauth ,controller.admin.main.getTypeInfo)
    router.post('/admin/addArticle',adminauth,controller.admin.main.addArticle)
}

注意,这里我们也使用了中间件,只要不登录是没办法操作这个接口的。

配置 apiUrl.js 文件

中台的接口配置完成后,还是按照惯例到/admin/src/config/apiUrl.js中配置接口的路径,代码如下:

let ipUrl = 'http://127.0.0.1:7001/admin/' 

let servicePath = {
    getTypeInfo:ipUrl + 'getTypeInfo' ,  //  获得文章类别信息
    addArticle:ipUrl + 'addArticle' ,  //  添加文章
    checkLogin:ipUrl + 'checkLogin' ,  //  检查用户名密码是否正确
}

export default servicePath;

编写 saveArticle 方法

现在可以利用 axios 来向数据库里添加文章信息了,代码如下:

//保存文章的方法
const saveArticle = () => {
    if (!selectedType) {
        message.error('必须选择文章类别')
        return false
    } else if (!articleTitle){
        message.error('文章名称不能为空')
        return false
    } else if (!articleContent){
        message.error('文章内容不能为空')
        return false
    } else if (!introducemd){
        message.error('简介不能为空')
        return false
    } else if (!showDate){
        message.error('发布日期不能为空')
        return false
    }

    let dataProps = {}   //传递到接口的参数
    dataProps.type_id = selectedType 
    dataProps.title = articleTitle
    dataProps.article_content = articleContent
    dataProps.introduce = introducemd
    let datetext = showDate.replace('-','/') //把字符串转换成时间戳
    dataProps.addTime = (new Date(datetext).getTime())/1000

    if(articleId==0){
        console.log('articleId=:'+articleId)
        dataProps.view_count = Math.ceil(Math.random()*100)+1000
        axios({
            method: 'post',
            url: servicePath.addArticle,
            data: dataProps,
            withCredentials: true
        }).then(
            res=>{
                setArticleId(res.data.insertId)
                if(res.data.isScuccess) {
                    message.success('文章添加成功')
                } else {
                    message.error('文章添加失败');
                }

            }
        )
    }
 }

这个方法编写完成后,可以到浏览器中进行微调,如果保存成功,说明我们的编写没有错误,

实现添加文章的方法

到这里我们虽然已经实现了文章加入数据库,但加入后如果我们再修改文章时,再点击保存按钮就会又新增加一条记录,这并不是我们想要的,这时候应该是修改,而不是重新增加一条新的数据。所以接下来我们就主要实现这个编辑保存功能。

编写中台接口方法

那要修改数据库里的记录,一定是通过中台接口来实现的,这时候我们需要在/service/app/controller/admin/main.js文件中,重新写一个方法updateArticle方法。

代码如下:

//修改文章
async updateArticle() {
    const tmpArticle = this.ctx.request.body
    const result = await this.app.mysql.update('article', tmpArticle);
    const updateSuccess = result.affectedRows === 1;
    console.log(updateSuccess)
    this.ctx.body = {
        isScuccess: updateSuccess
    }
}

编写完成后记得配置对应的路由,到/service/app/router/admin.js中修改代码。

module.exports = app => {
    const {router,controller} = app
    var adminauth = app.middleware.adminauth()
    router.get('/admin/index',controller.admin.main.index)
    router.get('/admin/getTypeInfo',adminauth ,controller.admin.main.getTypeInfo)
    router.post('/admin/addArticle',adminauth,controller.admin.main.addArticle)
    router.post('/admin/updateArticle',adminauth,controller.admin.main.updateArticle)
}

记得加上中间件的守护,这样才能保证不被恶意调用。这样中台部分就编写完成了。

后台 apiUrl.js 的配置

中台配置完成后,需要到后台里管理对应的请求路径文件,也就是/admin/src/config/apiUrl.js文件。

let ipUrl = 'http://127.0.0.1:7001/admin/' 

let servicePath = {
    getTypeInfo:ipUrl + 'getTypeInfo' ,  //  获得文章类别信息
    addArticle:ipUrl + 'addArticle' ,  //  添加文章
    updateArticle:ipUrl + 'updateArticle' ,  //  修改文章第 api 地址
    checkLogin:ipUrl + 'checkLogin' ,  //  检查用户名密码是否正确
}

export default servicePath;

这步完成后,后台管理页面就可以调用接口,修改数据库里的数据了。

后台保存方法的修改

在上面我们在保存文章时,使用了判断,if(articleId===0),如果等于 0 说明时新添加,如果不等于 0,说明时修改,那这时候只要修改else里的代码就可以完成修改操作了。

新添加的代码,也就是else中的代码:

else {
    dataProps.id = articleId 
    axios({
        method: 'post',
        url: servicePath.updateArticle,
        data: dataProps,
        withCredentials: true
    }).then(
        res => {
          if(res.data.isScuccess) {
              message.success('文章保存成功')
          } else {
              message.error('文章保存失败');
          }
        }
    )
}

为了方便你学习,我这里给出全部代码,你可以直接复制实现效果。

const saveArticle = () => {
    if(!selectedType){
        message.error('必须选择文章类型!');
        return false;
    } else if (!articleTitle) {
        message.error('文章名称不能为空!');
        return false;
    } else if (!articleContent) {
        message.error('文章内容不能为空!');
        return false;
    } else if (!introducemd) {
        message.error('文章简介不能为空!');
        return false;
    } else if (!showDate) {
        message.error('发布日期不能为空!');
        return false;
    }
    
    let dataProps = {}
    dataProps.type_id = selectedType;
    dataProps.title = articleTitle;
    dataProps.article_content = articleContent;
    dataProps.introduce = introducemd;
    let dataText = showDate.replace('-', '/');// 把字符串转换成时间戳
    dataProps.addTime = (new Date(dataText).getTime())/1000;

    if (articleId === 0) {
        dataProps.view_count =Math.ceil(Math.random()*100)+1000
        axios({
            method: 'post',
            url: servicePath.addArticle,
            data: dataProps,
            withCredentials: true
        }).then(
            res => {
                setArticleId(res.data.insertId);
                if(res.data.isSuccess){
                    message.success('文章添加成功');
                } else {
                    message.error('文章添加失败!');
                }
            }
        )
    } else {
        dataProps.id = articleId;
        axios({
            method: 'post',
            url: servicePath.updateArticle,
            data: dataProps,
            withCredentials: true
        }).then(
            res => {
                if(res.data.isSuccess){
                    message.success('文章保存成功');
                } else {
                    message.error('文章保存失败!')
                }
            }
        )
    }
}

这步完成,就可以实现修改文章的操作了,你可以到浏览器中去测试一下,再进行必要的微调操作。

实现修改文章

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » P32:后台管理系统开发11-实现添加文章的方法

发表回复