最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

Express GraphQl中的Cors

IT培训 admin 18浏览 0评论

Express GraphQl中的Cors

我通过在带有响应和表达的graphql中出现cors错误。

我已经尝试将proxy添加到react的package.json中,但是后来我明白了,无法将来自localhost:3000的请求/ graphql代理到http://127.0.0.1:5000。...

下面给出了反应代码

loadPosts = () => {

const graphqlQuery = {
  query: `
    {
      posts(page: ${page}) {
        posts {
          _id
          title
          content
          creator {
            name
          }
          createdAt
        }
        totalPosts
      }
    }
  `
};
fetch('graphql', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer ' + this.props.token,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(graphqlQuery)
})
  .then(res => {
    console.log(res)
    return res.json();
  })
  .then(resData => {
    if (resData.errors) {
      throw new Error('Fetching posts 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);

};

我已经尝试添加cors中间件以及选项标头,如您所见。

下面给出节点代码

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "OPTIONS, GET, POST, PUT, PATCH, DELETE"
  );
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  if (req.method === "OPTIONS") {
    return res.sendStatus(200);
  }
  next();
});

app.use(auth);

app.use(
  "/graphql",
  graphqlHttp({
    schema: graphqlSchema,
    rootValue: graphqlResolver,
    graphiql: true,
    formatError(err) {
      if (!err.originalError) {
        return err;
      }
      const data = err.originalError.data;
      const message = err.message || "An error occurred.";
      const code = err.originalError.code || 500;
      return { message: message, status: code, data: data };
    },
  })
);


回答如下:

代理错误:无法将请求/ graphql从本地主机:3000代理到http://127.0.0.1:5000这是一个代理错误,您的后端服务器已关闭并且无法访问,因此默认情况下,搜索为localhost:3000 / graphql

let yourCors= (req, res, next) => {
            res.setHeader("Access-Control-Allow-Origin", "*"); //http://127.0.0.1:3000
            res.setHeader(
            "Access-Control-Allow-Methods",
            "OPTIONS, GET, POST, PUT, PATCH, DELETE"
             );
            res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
            if (req.method === "OPTIONS") {
              return res.sendStatus(200);
            }
            next();
          }
let graphhttp= graphqlHttp({
                            schema: graphqlSchema,
                            rootValue: graphqlResolver,
                            graphiql: true,
                            formatError(err) {
                            if (!err.originalError) {
                                return err;
                            }
                            const data = err.originalError.data;
                            const message = err.message || "An error occurred.";
                            const code = err.originalError.code || 500;
                            return { message: message, status: code, data: data };
                            },
                          })

app.use("/graphql",
yourCors,
auth,
graphhttp

);
app.listen(port,()=>{console.log("connected")})

Express GraphQl中的Cors

我通过在带有响应和表达的graphql中出现cors错误。

我已经尝试将proxy添加到react的package.json中,但是后来我明白了,无法将来自localhost:3000的请求/ graphql代理到http://127.0.0.1:5000。...

下面给出了反应代码

loadPosts = () => {

const graphqlQuery = {
  query: `
    {
      posts(page: ${page}) {
        posts {
          _id
          title
          content
          creator {
            name
          }
          createdAt
        }
        totalPosts
      }
    }
  `
};
fetch('graphql', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer ' + this.props.token,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(graphqlQuery)
})
  .then(res => {
    console.log(res)
    return res.json();
  })
  .then(resData => {
    if (resData.errors) {
      throw new Error('Fetching posts 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);

};

我已经尝试添加cors中间件以及选项标头,如您所见。

下面给出节点代码

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "OPTIONS, GET, POST, PUT, PATCH, DELETE"
  );
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  if (req.method === "OPTIONS") {
    return res.sendStatus(200);
  }
  next();
});

app.use(auth);

app.use(
  "/graphql",
  graphqlHttp({
    schema: graphqlSchema,
    rootValue: graphqlResolver,
    graphiql: true,
    formatError(err) {
      if (!err.originalError) {
        return err;
      }
      const data = err.originalError.data;
      const message = err.message || "An error occurred.";
      const code = err.originalError.code || 500;
      return { message: message, status: code, data: data };
    },
  })
);


回答如下:

代理错误:无法将请求/ graphql从本地主机:3000代理到http://127.0.0.1:5000这是一个代理错误,您的后端服务器已关闭并且无法访问,因此默认情况下,搜索为localhost:3000 / graphql

let yourCors= (req, res, next) => {
            res.setHeader("Access-Control-Allow-Origin", "*"); //http://127.0.0.1:3000
            res.setHeader(
            "Access-Control-Allow-Methods",
            "OPTIONS, GET, POST, PUT, PATCH, DELETE"
             );
            res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
            if (req.method === "OPTIONS") {
              return res.sendStatus(200);
            }
            next();
          }
let graphhttp= graphqlHttp({
                            schema: graphqlSchema,
                            rootValue: graphqlResolver,
                            graphiql: true,
                            formatError(err) {
                            if (!err.originalError) {
                                return err;
                            }
                            const data = err.originalError.data;
                            const message = err.message || "An error occurred.";
                            const code = err.originalError.code || 500;
                            return { message: message, status: code, data: data };
                            },
                          })

app.use("/graphql",
yourCors,
auth,
graphhttp

);
app.listen(port,()=>{console.log("connected")})
11136

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论