Uncaught (in promise) SyntaxError: Unexpected token ‘<‘, “<!DOCTYPE “… is not valid JSON
Failed to load resource: the server responded with a status of 404 (Not Found)
i tried to decode it in backend and it doesnt getting resolved instead its jumping to catch block. i tried to resolve but unable to do so
my UserProfile.js
import React, { useEffect, useState, useContext } from 'react';
import { UserContext } from '../../App';
import { useParams } from 'react-router-dom';
const UserProfile = ({ match }) => {
const [userProfile, setUserProfile] = useState(null);
const { state, dispatch } = useContext(UserContext);
const userId = useParams()
useEffect(() => {
fetch(`/user/${userId}`, {
method:"GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
})
.then(resp => resp.json())
.then(result => {
setUserProfile(result);
});
}, []);
return (
<div style={{ maxWidth: "750px", margin: "0px auto" }}>
{userProfile ?
<div>
<div style={{
display: "flex",
justifyContent: "space-around",
margin: "18px 0px",
borderBottom: '1px solid gray'
}}>
<div>
<img style={{ width: "160px", height: "160px", borderRadius: "50%" }}
src="https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW4lMjBwcm9maWxlfGVufDB8fDB8fHww"
alt="profile" />
</div>
<div>
<h4>{userProfile.user.name}</h4>
<div style={{ display: "flex", justifyContent: "space-between", width: "108%" }}>
<h6>{userProfile.posts.length} Posts</h6>
{/* You can add Followers and Following counts here if needed */}
</div>
</div>
</div>
<div className='gallery'>
{userProfile.posts.map(item => {
return (
<img key={item._id} className="item" src={item.photo} alt="posts" />
);
})}
</div>
</div>
: <h2>Loading...</h2>
}
</div>
);
};
export default UserProfile;
my user.js //backend
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const requireLogin = require('../middleware/requireLogin'); // Middleware to check authentication
const User = mongoose.model("User");
const Post = mongoose.model("Post");
// Endpoint to fetch user profile details
router.get('/user/:userId', requireLogin, (req, res) => {
User.findOne({ _id: req.params.userId })
.select("-password") // Exclude password field
.then(user => {
Post.find({ postedBy: req.params.userId })
.populate("postedBy", "_id name") // Populate user details in posts
.then(( posts) => {
res.json({ user, posts });
});
})
.catch(err => {
return res.status(404).json({ error: "User not found" });
});
});
module.exports = router;
New contributor
Sudip S N is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.