问题的原因是项目ID在Apollo Client中未正确设置。需要在Apollo Client的配置文件中设置项目ID,以便在GraphQL mutation中使用。
代码示例:
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
// 设置项目ID
const projectID = "your-project-id";
const httpLink = new HttpLink({
uri: `https://graphql.fauna.com/graphql`,
});
const cache = new InMemoryCache();
const client = new ApolloClient({
link: httpLink,
cache,
headers: {
authorization: `Bearer ${process.env.FAUNADB_SERVER_SECRET}`,
'X-Schema-Preview': 'partial-update-mutation',
'X-Fauna-Source': 'JavaScriptExample',
// 使用项目ID
'X-FaunaDB-Project-Ref': `projects/${projectID}`,
},
});
// mutation
const ADD_TODO = gql`
mutation addTodo($todo: String!) {
createTodos(
data: {
todo: $todo
}
) {
todo
}
}
`;
client
.mutate({
mutation: ADD_TODO,
variables: { todo: "buy milk" }
})
.then(data => console.log(data))
.catch(error => console.error(error));
在这个例子中,我们设置了一个名为projectID
的变量,并将其添加到了Apollo Client的配置文件中,以便在mutation中使用。