I'm watching a tutorial and coding exactly as the instructor. I get this error at a point in the lesson. I get this error in my browser :
The below code is not mine, credits goes to maximilian schwarzmüller (Instructor).
Front End React function Responsible for loading posts :
loadPosts = direction => {
if (direction) {
this.setState({ postsLoading: true, posts: [] });
}
let page = this.state.postPage;
if (direction === "next") {
page++;
this.setState({ postPage: page });
}
if (direction === "previous") {
page--;
this.setState({ postPage: page });
}
const graphqlQuery = {
query: `
{
posts{
posts{
_id
title
content
creator {
name
}
createdAt
}
totalPosts
}
}
`
};
fetch("http://localhost:8080/graphql", {
method: "POST",
headers: {
Authorization: "Bearer " + this.props.token,
"Content-Type": "application/json"
},
body: JSON.stringify(graphqlQuery)
})
.then(res => {
return res.json();
})
.then(resData => {
if (resData.errors) {
throw new Error("Fetching Post Failed");
}
this.setState({
posts: resData.data.posts.posts.map(post => {
return {
...post,
imagePath: post.imageUrl
};
}),
totalPosts: resData.data.posts.totalPosts,
postsLoading: false
});
})
.catch(this.catchError);
};
Server code attached : REMOVED
I'm attaching my whole code because I really don't know where the error is coming from. I basically replicated my instructor's code but it didn't work in mine like his did. The Udemy community was also unable to help.
EDIT : I found the problem, it was my mistake, I redirected with 401 in my token checking if block. I did exactly the opposite, I redirected if the user was authenticated.