繁体   English   中英

为什么我收到 403 错误并且我的 Delete API 无法从前端工作

[英]why I am getting an 403 error and my Delete API not working from front-end

我是新手,请帮助我,我正在从事 MERN 项目,但不知道如何让我的 Delete API 从前端工作。 当我从 Postman 测试它时,删除 API 正在工作,但从前端尝试时它不起作用。

这是我删除 API 的代码

//delete a post

router.delete("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
     if (post.userId === req.body.userId) {
      await post.deleteOne();
      res.status(200).json("the post has been deleted");
    } else {
      res.status(403).json("you can delete only your post");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

我做了一个按钮和删除操作

<button className="postdeletebutton" onClick={deleteHandler} >Delete</button>

我还添加了 deletehandler 假设执行删除操作

const deleteHandler = () => {
  try {
    axios.delete("/posts/" + post._id, {userId: "6245aebc58a3a42100e43e94"});
    } catch (err){}
};

喜欢,不喜欢和添加帖子在前端工作正常,但删除不起作用我在终端中收到 403 错误,正如我在后端提到的那样,我也尝试对用户 ID 进行硬编码,但它不起作用

这是 Post.JSX 的完整代码

import "./post.css";
import React from "react";
import { MoreVert } from "@material-ui/icons";
import IconButton from "@material-ui/core/IconButton";
import MenuItem from "@material-ui/core/MenuItem";
import Menu from "@material-ui/core/Menu";
import { useContext, useEffect, useState, useRef} from "react";
import axios from "axios";
import { format } from "timeago.js";
import { Link } from "react-router-dom";
import { AuthContext } from "../../context/AuthContext";
import { PermMedia, Cancel } from "@material-ui/icons";


export default function Post({ post }) {
  const [like, setLike] = useState(post.likes.length);
  const [isLiked, setIsLiked] = useState(false);
  const [user, setUser] = useState({});
  const PF = process.env.REACT_APP_PUBLIC_FOLDER;
  const { user: currentUser } = useContext(AuthContext);

  useEffect(() => {
    setIsLiked(post.likes.includes(currentUser._id));
  }, [currentUser._id, post.likes]);

  useEffect(() => {
    const fetchUser = async () => {
      const res = await axios.get(`/users?userId=${post.userId}`);
      setUser(res.data);
    };
    fetchUser();
  }, [post.userId]);


  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const open = Boolean(anchorEl);

  const handleClose = () => {
    setAnchorEl(null);
  };

  const likeHandler = () => {
    try {
      axios.put("/posts/" + post._id + "/like", { userId: currentUser._id });
    } catch (err) {}
    setLike(isLiked ? like - 1 : like + 1);
    setIsLiked(!isLiked);
  };

const deleteHandler = () => {
  try {
    axios.delete("/posts/" + post._id, {userId: "6245aebc58a3a42100e43e94"});
    } catch (err){}
};

//temp
// const [file, setFile] = useState(null);
// const desc = useRef();

// const submitHandler = async (e) => {
//   e.preventDefault();
//   const newPost = {
//     userId: user._id,
//     desc: desc.current.value,
//   };
//   if (file) {
//     const data = new FormData();
//     const fileName = Date.now() + file.name;
//     data.append("name", fileName);
//     data.append("file", file);
//     newPost.img = fileName;
//     console.log(newPost);
//     try {
//       await axios.post("/upload", data);
//     } catch (err) {}
//   }
//   try {
//     await axios.post("/posts", newPost);
//     window.location.reload();
//   } catch (err) {}
// };
//temp

  return (
    <div className="post">
      <div className="postWrapper">
        <div className="postTop">
          <div className="postTopLeft">
            <Link to={`/profile/${user.username}`}>
              <img
                className="postProfileImg"
                src={
                  user.profilePicture
                    ? PF + user.profilePicture
                    : PF + "person/noAvatar.png"
                }
                alt=""
              />
            </Link>
            <span className="postUsername">{user.username}</span>
            <span className="postDate">{format(post.createdAt)}</span>
          </div>

          <IconButton
          aria-label="more"
          onClick={handleClick}
          aria-haspopup="true"
          aria-controls="long-menu"
          >
            <MoreVert />
          </IconButton>

          {currentUser._id === post.userId && (
          <Menu 
          anchorEl={anchorEl} 
          keepMounted onClose={handleClose} 
          open={open}>
            <MenuItem
            onClick={handleClose}
            >
              <button className="posteditbutton" >Edit &nbsp;</button>

              <button className="postdeletebutton" onClick={deleteHandler} >Delete</button>
            </MenuItem>
         </Menu>
         )}

         {/* temp */}


         {/* <hr className="shareHr" />
        {file && (
          <div className="shareImgContainer">
            <img className="shareImg" src={URL.createObjectURL(file)} alt="" />
            <Cancel className="shareCancelImg" onClick={() => setFile(null)} />
          </div>
        )}
        <form className="shareBottom" onSubmit={submitHandler}>
          <div className="shareOptions">
            <label htmlFor="file" className="shareOption">
              <PermMedia htmlColor="tomato" className="shareIcon" />
              <span className="shareOptionText">Add Photo</span>
              <input
                style={{ display: "none" }}
                type="file"
                id="file"
                accept=".png,.jpeg,.jpg"                        
                onChange={(e) => setFile(e.target.files[0])}
              />
            </label>

          </div>
          <button className="shareButton" type="submit">
            Share
          </button>
        </form> */}

         {/* temp */}
  
        </div>
        <div className="postCenter">
          <span className="postText">{post?.desc}</span>
          <img className="postImg" src={PF + post.img} alt="" />
        </div>
        <div className="postBottom">
          <div className="postBottomLeft">
            <img
              className="likeIcon"
              src={`${PF}like.png`}
              onClick={likeHandler}
              alt=""
            />
            <img
              className="likeIcon"
              src={`${PF}heart.png`}
              onClick={likeHandler}
              alt=""
            />
            <span className="postLikeCounter">{like} people Appreciate it</span>
          </div>
          {/* <div className="postBottomRight">
            <span className="postCommentText">{post.comment} comments</span>
          </div> */}
        </div>
      </div>
    </div>
  );
}

你能打印在 try catch 块中收到的错误并给我们消息吗?

错误是我使用的数据类型=== 并且我们仅在我们有值 + 数据类型时使用它,但在我的情况下,我们只有值所以而不是在 API 中使用 === 我使用 == 并且它在这里有效它的代码

特别感谢在这方面帮助我的 Saad 先生

//delete a post

router.delete("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
     if (post.userId === req.body.userId) {
      await post.deleteOne();
      res.status(200).json("the post has been deleted");
    } else {
      res.status(403).json("you can delete only your post");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

//delete a post
router.delete("/:id", async (req, res) => {
try {
    const post = await Post.findById(req.params.id);

    if (post._id == req.params.id) {
      await post.deleteOne();
      res.status(200).json("the post has been deleted");
    } else {
      res.status(403).json("you can delete only your post");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

我也在前端做了些微改动

const deleteHandler = () => {
    try {
      axios.delete("/posts/" + post._id);
    } catch (err) { }
  };

这就是现在删除按钮的样子

<button className="postdeletebutton" onClick={deleteHandler} >Delete</button>

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM