I am working on developing social media app using MERN Stack. First I made it to create post with img, description ans title and display in wall, it works well. but later I wanted to update it to display username with creator’s name. Now I get message ‘Error fetching from server’. this is my post schema and user schema.
const PostSchema = new mongoose.Schema(
{
img: [{type:String}],
title: {type: String, required:true, unique:true},
description: {type:String},
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
comments: [CommentSchema],
react: [ReactionSchema]
},
{timestamps: true}
);
module.exports = mongoose.model("Post", PostSchema);
const mongoose = require("mongoose")
const UserSchema = new mongoose.Schema({
firstname: {type: String, required:true},
secondname: {type: String, required:true},
email:{type:String, required:true, unique: true },
password: {type:String, required:true},
age:{type:String},
profilePicture: { type: String },
isAdmin:{
type: Boolean, default:false
}
},
{timestamps: true}
);
const User = mongoose.model('users', UserSchema);
module.exports = User;
this is the front end.
import React from 'react';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Filter from './Filter';
import SocialPost from './SocialPost';
import { useState, useEffect } from 'react';
import axios from 'axios';
export default function Wall() {
const [posts, setPosts] = useState([]);
const [error, setError] = useState([]);
useEffect(() => {
axios.get('http://localhost:5000/getPosts')
.then(res => {
if(res.data.status === 'success' && res.data.data.posts){
const Posts = res.data.data.posts;
setPosts(Posts);
}else{
setError('Unexpected response format from server');
}
})
.catch(err => {
if(err.response && err.response.status === 403){
setError('Access Denied');
}else{
setError('Error fetching from server');
}
});
},[]);
return (
<>
<Container>
<Row>
<Col> <Filter/> </Col>
<Col xs={6}>
<div style={{ maxHeight: "calc(100vh - 100px)", overflowY: "auto" }}>
<SocialPost/>
{
posts.map((post,index) => (
<SocialPost
key = {index}
img = {post.img}
title = {post.title}
description = {post.description}
username={post.user.username}
id = {post._id}
/>
))}
{error && <p style={{color:'red'}}>{error}</p>}
</div>
</Col>
<Col>3 of 3</Col>
</Row>
</Container>
</>
)
}
import React from "react";
import Card from "react-bootstrap/Card";
import ListGroup from "react-bootstrap/ListGroup";
import Image from "react-bootstrap/Image";
//import Row from 'react-bootstrap/Row';
const SocialPost = ({img,title,description, username}) => {
return (
<>
<Card style={{ width: "38rem" , margin:"10px"}}>
<Card.Header variant="dark">
<Image src="fgh" roundedCircle className="me-2 avatar-sm" />
Artist Name{" "}
{username}
</Card.Header>
<ListGroup className="list-group-flush">
<ListGroup.Item><Card.Title>{title}</Card.Title>
<Card.Text>
{description}
</Card.Text></ListGroup.Item>
</ListGroup>
<Card.Img variant="top" src={img} />
<Card.Body>
<Card.Text className="size=sm">12 views</Card.Text>
<Card.Text>
<i class="bi bi-chat"></i> Comment
</Card.Text>
</Card.Body>
</Card>
</>
);
}
export default SocialPost;
This is the back end.
const router = require("express").Router();
const Post = require("../Database/models/posts")
router.get("/", async(req, res) => {
try {
const posts = await Post.find({}).populate('author', 'firstname secondname');
const formattedPosts = posts.map(post => ({
...post._doc,
user: {
firstname: post.author.firstname,
secondname: post.author.secondname,
username: `${post.author.firstname} ${post.author.secondname}`
}
}));
res.status(200).json({
status: 'success',
data: {
posts: formattedPosts
}
});
} catch (err) {
res.status(500).json({
status: 'Failed',
message: err.message
});
}
});
module.exports = router;
Please help me to find issue here and correct it.
2
Answers
Potential Issues and Debugging
You haven’t mentioned CORS in the code snippets you provided. CORS (Cross-Origin Resource Sharing) is necessary if your frontend and backend run on different origins (e.g., ports like localhost:3000 for frontend and localhost:5000 for backend).
To enable CORS in your Express backend, you can use the CORS middleware.
You should not be
else
-ing in a successful fetch and checking&& res.data.data.posts
in the sameif
statement that checks for a successful network request.If you’re using array of errors, the variable should be called
errors
, noterror
.Your
Post.find({})
should be passed in areq
data. It seems empty right now.You should also explicitly handle a case of a
null
formattedPosts
result.Lastly, please post a
network
tab result of the request. The only information that we get from your post above is that the client request is failing, but not because of403
.To me, it is unclear which part of the req/res chain is causing your record is failing. But above modifications should get you closer to the source.