【发布时间】: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