美文网首页
(十三)Node接口搭建——编辑和删除信息接口

(十三)Node接口搭建——编辑和删除信息接口

作者: 彼得朱 | 来源:发表于2019-07-09 12:04 被阅读0次

    1、编写编辑接口,也需要token (在api/profiles.js中)

    // $route POST api/profiles/edit
    // @desc 编辑信息接口  ,第二个参数会验证我们的token
    // @access Private
    router.post("/edit/:id",passport.authenticate("jwt", {session: false}),(req,res)=>{
    
        const profileFields = {};
        
        if(req.body.type) profileFields.type = req.body.type;
        if(req.body.describe) profileFields.describe = req.body.describe;
        if(req.body.income) profileFields.income = req.body.income;
        if(req.body.expend) profileFields.expend = req.body.expend;
        if(req.body.cash) profileFields.cash = req.body.cash;
        if(req.body.remark) profileFields.remark = req.body.remark;
    
        Profile.findOneAndUpdate(
            {_id:req.params.id},
            {$set:profileFields},
            {new:true}
        ).then(profile => res.json(profile));
    });
    

    测试:(记得写token)

    测试编辑接口

    以前查询的:

    以前的

    现在查询的:

    现在的

    说明编辑接口编写成功。

    2、删除信息接口,同样需要token, (在api/profiles.js中)

    删除成功后把删除的信息返回。这样可以看效果

    // $route delete api/profiles/delete
    // @desc 删除信息接口  ,第二个参数会验证我们的token
    // @access Private
    router.delete(
        '/delete/:id',
        passport.authenticate("jwt", {session: false}),
        (req,res) => {
            Profile.findOneAndDelete({_id:req.params.id})
            .then(profile => {
                // 删除成功后返回删除的信息
                profile.save().then(profile => res.json(profile));
            })
            .catch(err => res.status(404).json('删除失败!'));
        }
    );
    
    

    测试:(记得写token)

    测试删除接口 现在的

    再次查询,现在只看到一项信息了,说明编写删除接口成功。

    相关文章

      网友评论

          本文标题:(十三)Node接口搭建——编辑和删除信息接口

          本文链接:https://www.haomeiwen.com/subject/hjqxkctx.html