要解决Apollo Server中的GraphQL Mutation查询无效的问题,你可以尝试以下几个步骤:
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Query {
hello: String
}
type Mutation {
updateHello(name: String!): String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello World',
},
Mutation: {
updateHello: (_, { name }) => `Hello ${name}`,
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`Server running at ${url}`);
});
确保你的Mutation查询在Schema中正确定义,并且名称和参数与resolver中的定义匹配。
确保在客户端正确调用Mutation查询。以下是一个使用Apollo Client发送Mutation查询的示例:
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'http://localhost:4000', // Apollo Server的URL
cache: new InMemoryCache(),
});
const UPDATE_HELLO = gql`
mutation UpdateHello($name: String!) {
updateHello(name: $name)
}
`;
client
.mutate({
mutation: UPDATE_HELLO,
variables: { name: 'Alice' },
})
.then(({ data }) => {
console.log(data.updateHello); // 输出:Hello Alice
})
.catch((error) => {
console.error(error);
});
确保在代码中正确使用了Mutation查询,并传递了正确的参数。
如果你仍然遇到问题,可以通过提供更多的代码示例和错误信息来进一步描述你的问题,这样我就能更好地帮助你解决。