在graphQL中请求帖子列表会导致Node js错误

时间:2019-10-31 18:51:20

标签: node.js reactjs express graphql express-graphql

我正在观看教程,并且完全按照讲师的要求进行编码。我在课程中的某个时刻遇到了这个错误。我在浏览器中收到此错误:enter image description here 以下代码不是我的,应归功于maximilianschwarzmüller(讲师)。

前端React功能负责加载帖子:

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);
  };

附加的服务器代码:已删除

我要附加我的整个代码,因为我真的不知道错误是从哪里来的。我基本上复制了老师的代码,但是在我的代码中却没有像他的代码那样起作用。 Udemy社区也无法提供帮助。

编辑:我发现了问题,这是我的错误,我在令牌检查中使用401重定向了是否阻止。我做的恰恰相反,如果用户通过了身份验证,则会重定向。

0 个答案:

没有答案