问题描述
我在前端(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客户端安装程序在运行时将Authorization标头添加到我的graphql请求中。但是在构建时,由于没有可用的标头,我遇到了错误。 在构建期间要发送的标头我缺少什么?还是可以以某种方式检测在构建期间是否触发了呼叫,以便忽略身份验证过程? 非常感谢。
解决方法
感谢@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