【问题标题】:Setting a test header in GraphQL Playground that I want to use causes "Server cannot be reached"在我想使用的 GraphQL Playground 中设置测试标头会导致“无法访问服务器”
【发布时间】:2019-05-21 11:58:53
【问题描述】:

所以我创建了一堆突变和查询,并将它们拼接在一起,并且希望将身份验证引入组合中。我添加了一个 HTTP 标头“x-token”来保存我的登录令牌,以便能够删除他们的工作或用户本身等内容。

const getMe = async req => {
  const token = req.headers['x-token'];

  if (token) {
    try {
      return await jwt.verify(token, "notSoSecret");
    } catch (e) {
      throw new AuthenticationError(
        'Your session expired. Sign in again.',
      );
    }
    }
  };

  const server = new ApolloServer({
    typeDefs: schema,
    resolvers,
    formatError: error => {
      // remove the internal sequelize error message
      // leave only the important validation error
      const message = error.message
        .replace('SequelizeValidationError: ', '')
        .replace('Validation error: ', '');

      return {
        ...error,
        message,
      };
    },
    context: async ({ req }) => {
      const me = await getMe(req);

      return {
        models,
        me,
        secret: "notSoSecret",
      }
    },
    path: "/graphql"
  });

  server.applyMiddleware({ app });


  sequelize.sync().then(async () => {
     createUsersWithJob();
  });

  app.get("/playground", graphiql({ endpoint: "/graphql" }));
  const handler = serverless(app);
  export { handler };

  const createUsersWithJob = ... //creates seed data

所以当我添加令牌并查看我的命令行控制台时,我实际上看到我正在设置我想要的标题,但它一遍又一遍地循环并且不会停止。游乐场也收到错误“无法访问服务器”

{
  "error": "Response not successful: Received status code 400"
}

在我删除我在操场上设置的 HTTP 标头之前,运行 deleteUser 突变或任何其他突变和查询都不起作用。

还有一个次要问题,即此根文件中的所有内容都运行了两次,但目前对我来说并没有标题问题概述的那么大。

如果有人对此有任何见解,我很想知道更多。提前致谢。

编辑:只是快速编辑说当我硬编码一个预先存在的用户时它可以正常工作。

【问题讨论】:

    标签: node.js sequelize.js graphql apollo serverless


    【解决方案1】:

    我很难让 GraphQL Playground 的 React 版本在一个非常简单的 html 设置中运行,但我想出了一些可能对你也有帮助的东西(祈祷)。

    我在GraphQLPlayground.init 调用的配置中添加了一个headers 部分,如下所示:

    const root = document.getElementById('root');
    GraphQLPlayground.init(root, {
      endpoint: "/graphql",
      headers: {
        "Authorization": "Bearer " + token
      }
    })
    

    我有一个 ID 为 root 的元素,因为它嵌入在 HTML 中。

    不确定这是否会对您有所帮助,因为我刚刚从您的代码示例中注意到您正在调用 graphiql,这是与 GraphQL Playground 不同的 GraphQL 客户端..

    GraphIQL:https://github.com/skevy/graphiql-app
    GraphQL 操场:https://github.com/prisma/graphql-playground

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 2013-12-24
      • 2015-11-01
      • 2020-02-07
      • 2015-02-18
      • 2022-07-06
      • 2019-09-24
      • 2021-05-10
      • 2017-11-09
      相关资源
      最近更新 更多