【问题标题】:like/dislike button with api call not working using vue an mongoDBapi调用的喜欢/不喜欢按钮无法使用vue an mongoDB
【发布时间】:2022-08-03 15:58:34
【问题描述】:

我正在学习 vuejs,我正在做我的第一个项目,这是一个社交网络,我想实现一个点赞按钮,如果用户已经喜欢它,它会调用 api 来添加或删除它。它确实在我的后端工作,但我不能让它在前面工作。 单击按钮时,我需要发送 userId 并添加或删除类似内容

这是数据

data() {
        return {
            post: {
                file: \"\",
                content: \"\",
                likes: 0,
            },
            showModal: false,
            showModifyPost: false,
            user: {
                firstname: \"\",
                lastname: \"\",
                _id: \"\",
            },

        };
    },

我尝试的最后一种方法

likePost(id) {
            axios
                .post(\'http://127.0.0.1:3000/api/post/like/\' + id, {
                    headers: {
                        Authorization: \"Bearer \" + localStorage.getItem(\"token\"),
                    },
                })
                .then(() => {
                    console.log(\"response\", response);
                    this.user._id = response.data._id;
                    if(post.usersLiked == user._id) {
                        this.post.likes += 0
                    } else if (post.usersLiked != user._id) {
                        this.post.likes += 1
                    };
                })
                .catch((error) => console.log(error));
        }

这就是模型

const postSchema = mongoose.Schema({
    userId: { type: String, required: true, ref: \"User\" },
    content: { type: String, required: true, trim: true },
    imageUrl: { type: String, trim: true },
    likes: { type: Number, default: 0 },
    usersLiked: [{ type: String, ref: \"User\" }],
    firstname: {type: String, required: true, trim: true },
    lastname: {type: String, required: true, trim: true },
    created_at: { type: Date},
    updated_at: { type: Date }
});

知道有什么问题吗?谢谢 !

  • D B正确更新?
  • 你说它在前端不起作用是什么意思?方法未触发,API 调用返回错误数据,模板未刷新?
  • 它不会在数据库上更新,我收到错误 401(未经授权)。

标签: vue.js


【解决方案1】:
.then(() => { // you missed value response from Promise here
  this.user._id = response.data._id;
  if(post.usersLiked == user._id)
})

你的意思是this.post.usersLiked === user._id 我想,所以在你的数据选项应该

post: {
  file: "",
  content: "",
  likes: 0,
  usersLiked: false,
  // something else reflect to your post schema
},

如果用户已经喜欢它,我想实现一个调用 api 添加喜欢或删除它的喜欢按钮

通过说您只需要一个简单的boolean 值来执行此操作

likePost(id) {
  axios
    .post('http://127.0.0.1:3000/api/post/like/' + id, {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token"),
      },
    })
    .then((response) => {
      // Just need to toggle state
      this.$set(this.post, 'usersLiked', this.post.usersLiked !== response?.data?._id)
    })
    .catch((error) => console.log(error));
}

【讨论】:

  • 我收到错误 401(未经授权)。我猜是因为令牌。但是所有其他需要令牌的方法都在工作,所以我现在有点困惑
  • 我在 api 路由旁边添加了 this.post。该错误不再出现,但现在没有任何反应
  • 您可以在选项卡中检查您的 API网络查看它是否在标头中附加了令牌以及来自它的响应。
  • 我确实有一个带有不记名令牌的标题,但响应是空的,我没有状态代码。
  • 但在用户喜欢的数据中,我想拥有喜欢它的用户的所有 id。所以做一个布尔值可能行不通?
【解决方案2】:

找到了答案,我把axios方法改成了这个

likePost(id) {
            let userId = localStorage.getItem('userId');
            axios
                .post('http://127.0.0.1:3000/api/post/like/' + id, { userId }, {
                    headers: {
                        Authorization: "Bearer " + localStorage.getItem("token"),
                    },
                })
                .then((response) => {
                    console.log(response.data);
                    this.getAllPost();
                })
                .catch((error) => console.log(error));
        }

我还对数据进行了一些更改

data() {
        return {
            posts: [],
            post: {
                file: "",
                content: "",
            },
            showModal: false,
            showModifyPost: false,
            user: {
                firstname: "",
                lastname: "",
                _id: "",
            },
        };
    },

我还对控制器进行了一些更改

exports.ratePost = (req, res, next) => {
    console.log(req.body.userId)
    //using findOne function to find the post
    Post.findOne({ _id: req.params.id }).then(post => {
        if (!post.usersLiked.includes(req.body.userId)) {
            // making a object with $inc and $push methods to add a like and to add the user's id
            let toChange = {
                $inc: { likes: +1 },
                $push: { usersLiked: req.body.userId },
            };
            // we update the result for the like
            Post.updateOne({ _id: req.params.id }, toChange)
                // then we send the result and the message
                .then(post =>
                    res
                        .status(200)
                        .json(
                            { message: "Liked !", data: post }
                        )
                )
                .catch(error => res.status(400).json({ error }));
        } else if (post.usersLiked.includes(req.body.userId)) {
            // using the updateOne function to update the result
            Post.updateOne(
                { _id: req.params.id },
                //  we use a pull method to take off a like
                { $pull: { usersLiked: req.body.userId }, $inc: { likes: -1 } }
            )
                .then(post => {
                    // then we send the result and the message
                    res
                        .status(200)
                        .json(
                            { message: "Post unliked", data: post }
                        );
                })
                .catch(error => res.status(400).json({ error }));
        }
    });
};

【讨论】:

    猜你喜欢
    • 2012-09-20
    • 2014-09-21
    • 2017-09-06
    • 2016-04-04
    • 2019-07-03
    • 1970-01-01
    • 2017-08-25
    • 2020-11-04
    • 2012-09-09
    相关资源
    最近更新 更多