I now deployed my MERN web app via vercel. Unfortunately, I encountered the above error that is actually not existent with my localhost. In which, pinpoints to the line .then(data =>
of this block of code:
useEffect(() => {
fetch(`${process.env.API_URL}/users/profile`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem('token')}`
}
})
.then(res => res.json())
// console.log(res.status) added this just to check if it returns 200 and it is
.then(data => {
console.log(data)
if(typeof data._id !== "undefined") {
setUser({
id: data._id,
isAdmin: data.isAdmin
})
} else {
setUser({
id: null,
isAdmin: null
})
}
})
}, [])
I checked my API via Postman and it returns as
{
"auth": "failed"
}
It is also the same output as I console.log(). But this is actually an expected output since the error was on my App.js and it doesn't need to logged in yet. I just don't know why it is not returned as JSON and I also try to return it as false either but still return the auth error.
For more reference this is my API route and controller
router.get("/profile", auth.verify, (req, res) => {
const userData = auth.decode(req.headers.authorization)
if(userData){
userController.getProfile({id: userData.id}).then(result=> res.send(result))
} else {
res.send(false)
}
});
module.exports.getProfile = (reqBody) => {
return User.findById(reqBody.id).then((result, error) => {
if(error){
return false
} else {
if(result == null){
return false
} else {
result.password = "************"
return result
}
}
})
};
This is the only error I need to resolve to make my web app function correctly. I hope you will help me. Thanks a lot!
CodePudding user response:
So, I have solved my own problem and successfuly deployed my web app via Vercel.
I checked my Vercel app and try other functions such as login and register. It turns out that my API URL is undefined
. So, I presume that did not clicked the add button in setting environment variables during the deployment.
I created a new deployment with new repository since I did not figured out how to delete my pre-existing deployed app. I now make sure to click the add button once I entered my environment variables and its URL before clicking the Deploy button.