最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何使用 Axios 和 MongoDB 在我的 MERN 时间线中成功呈现来自不同用户的帖子?

网站源码admin19浏览0评论

如何使用 Axios 和 MongoDB 在我的 MERN 时间线中成功呈现来自不同用户的帖子?

如何使用 Axios 和 MongoDB 在我的 MERN 时间线中成功呈现来自不同用户的帖子?

`考虑到我的 MongoDB 中有数据,当我使用 axios 获取数据时出现请求失败错误。我可以用什么方法解决这个问题?基本上这是一个社交媒体应用程序。我正在尝试从所有用户那里获取所有帖子并将其呈现在提要组件上。

这是错误

{message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

**这是我的 fetchUser 的 users.js 中的端点**:

//Get a user
router.get('/:id', async (request, response) => {
    try {
        const user = await User.findById(request.params.id);
        const {password, updatedAt, ...other} = user._doc
        response.status(200).send(other);
    } catch(error){
        response.status(404).send({error: "User not found"});
    }
});

这是我前端的 Post.js:

const Post = ({ post }) => {
  console.log(post)//Shows post in an array of objects
  const [user, setUser] = useState({});

  useEffect(() => {
    const fetchUser = async () => {
      const response = await axios.get(`http://localhost:8080/api/v1/users/${post.userId}`);
      setUser(response.data);
      console.log(response)
    };
    fetchUser();
  }, [post.userId]);

我的 fetchPosts 的端点

router.get('/timeline/:userId', async(request, response) => {
    try{
        const currentUser = await User.findById(request.params.userId);
        const userPosts = await Post.find({ userId: currentUser._id });
        const friendPosts = await Promise.all(
            currentUser.following.map((friendId) => {
                return Post.find({ userId: friendId });
            })
        );
        response.status(200).json(userPosts.concat(...friendPosts))
    } catch(error){
        response.status(500).send({error: "No posts found"});
    }
});

Feed.js 我在哪里获取帖子并将其作为 Post.js 中的道具传递:

const Feed = () => {

    const [posts, setPosts] = useState([])

    useEffect(() => {
        const fetchPosts = async () => {
            const response = await axios.get('http://localhost:8080/api/v1/posts/timeline/6461bf3e6f1deca292fd2fb8/')
            setPosts([response.data])
        }
        fetchPosts();
    }, []);

    return (
        <div className='feed'>
            <PostForm/>
            {posts.map((p) => (
                <Post key={p._id} post={p}/>
            ))};
        </div>
    );
};

我的 Post.js 和 User.js 的模型:

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema(
    {
        userId:{
            type: String,
            required: true
        },
        desc:{
            type: String,
            max: 500
        },
        img:{
            type: String,
        },
        likes:{
            type:Array,
            default:[],
        },
    },
    { timestamps: true }
);

module.exports = mongoose.model('Post', PostSchema);
const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    username:{
        type:String,
        require: true,
        min: 3,
        max: 20,
        unique: true
    },
    email: {
        type: String,
        require: true,
        max: 50,
        unique: true
    },
    password: {
        type: String,
        required: true,
        min: 6
    },
    profilePicture: {
        type: String,
        default: ""
    },
    coverPicture: {
        type: String,
        default: ""
    },
    followers: {
        type: Array,
        default: []
    },
    following: {
        type: Array,
        default: []
    },
    isAdmin: {
        type: Boolean,
        default: false,
    },
    desc: {
        type: String,
        max: 50
    },
    from: {
        type: String,
        max: 50
    }
},
{timestamps: true}
);

module.exports = mongoose.model('User', UserSchema);

我在我的 Post.js 上尝试了 console.log(post),它返回一个对象数组,其中包含我来自不同用户的帖子数据。

我也试过了

const response = await axios.get(
http://localhost:8080/api/v1/users/${post[0].userId}
);

很明显它只显示索引 0 上的数据。在我的 jsx 中,当我像 {post[0].username} 或 {post[0].desc] 等调用它们时它也有效。

因为基本上我想在我的时间轴端点上显示来自不同用户的所有帖子,是否有针对此问题的可靠解决方案?

一段时间以来一直在努力寻找解决方案,这让我无处可去。`

回答如下:
发布评论

评论列表(0)

  1. 暂无评论