【问题标题】:Graphql request at Gatsby build-time doesn't send headersGatsby 构建时的 Graphql 请求不发送标头
【发布时间】:2020-12-23 02:07:19
【问题描述】:

我在前端 (Gatsby) 和 pollo 之间添加了身份验证。这适用于运行时的请求。然而,在构建时,没有任何标头不会发送到 Apollo。我有以下代码:

// SERVER SIDE
// apollo server setup
const { ApolloServer, AuthenticationError } = require("apollo-server-lambda")
... //other imports

const server = new ApolloServer({
  context: ({ event, context }) => {
    if (!event.headers.authorization) {
        // No authentication header
        throw new AuthenticationError("must authenticate")
    }
    // Authenticate
  },
  resolvers,
  schema: schemaWithResolvers,
  introspection: true,
  playground: true,
  formatError: (err) => {
    console.log("Error", err)
    return err
  },
})
// CLIENT SIDE
// apollo-client setup
import { ApolloClient } from "apollo-client"

const client = new ApolloClient({
    link: ApolloLink.from([
        onError (.......),
        new HttpLink({
          uri: process.env.REACT_APP_GQL_SERVER,
          credentials: "same-origin",
          headers: {
            Authorization: 'Basic ' + '<login>:<password>', //works at run-time, not at build-time
          },
        }),
      ]),
  cache: new InMemoryCache(),
  fetch,
})
// CLIENT SIDE
// gatsby-node (during build-time)
// => This call gets rejected during buildtime because authorization header is not available.
exports.createPages = async function ({ actions, graphql }) {
  const { data } = await graphql(`
    query {
      apollo {
        allWathever {
          id
        }
      }
    }
  `)
}

我的 apollo-client 设置在运行时将 Authorization 标头添加到我的 graphql 请求中。但是在构建时我收到错误,因为没有可用的标题。 在构建时发送标头我缺少什么?或者我可以以某种方式检测在构建时是否触发了呼叫,以便我可以忽略身份验证过程? 非常感谢。

【问题讨论】:

  • graphql() 在构建时调用在节点环境中工作(将运行时服务器/客户端分开)...定向到内部 gatsby '服务器',单独配置客户端以进行构建或使用某些源插件用于外部 graphql api 访问,配置它等。
  • 所以我应该在我的服务器端添加一个 ApolloClient 吗?就在 ApolloServer 旁边?

标签: javascript graphql react-apollo apollo-client apollo-server


【解决方案1】:

感谢@xadm,我发现要在构建时使用源数据,您需要安装一个插件并将其添加到您的配置中。我使用 gatsby-source-graphql 并忘记在此处添加标题。

//gatsby-config-js
    {
      resolve: "gatsby-source-graphql",
      options: {
        typeName: "Apollo",
        fieldName: "apollo",
        createLink: (pluginOptions) => {
          return createHttpLink({
            uri: "your uri",
            fetch,
            credentials: "same-origin",
            headers: {
              Authorization: "your authorization",
            },
          })
        },
      },
    },

关于此的文章:https://www.gatsbyjs.com/docs/data-fetching/#fetching-data-at-build-time

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2023-04-01
    • 2019-10-24
    • 1970-01-01
    相关资源
    最近更新 更多