访问GraphQL服务GraphiQL界面时提示“Must provide query string”错误的排查求助
Hey there! Let's break down what's causing that error and fix the other sneaky issues in your code so your GraphQL service works as expected.
1. The Immediate Fix for the Query String Error
The main reason you're seeing {"errors":[{"message":"Must provide query string."}]} is a typo in the GraphiQL configuration.
In your graphqlHTTP setup, you wrote graphql:true—but the correct parameter to enable the browser-based GraphQL playground is graphiql:true. Without this, hitting localhost:5000/graphql just expects a raw query string instead of showing the interactive interface.
Update this line:
app.use('/graphql', graphqlHTTP({ schema:schema, graphiql:true }))
2. Fixing Other Critical Code Issues
Even after fixing the GraphiQL typo, your mutation will fail due to spelling and syntax errors. Let's clean those up:
2.1 Mutation Resolver Typos & Syntax Errors
In the createUser resolver, there are a few mistakes:
args.usename→ should beargs.username(you missed an 'r')adress: args,company,→ double mistake here:adressis misspelled (should beaddress), andargs,companyis a syntax error (it should beargs.address)
Here's the corrected resolver:
resolve(parent, args) { const newUser = { email: args.email, username: args.username, name: args.name, company: args.company, address: args.address }; users.push(newUser); return newUser; }
2.2 Ensure Proper Object Closing
Your RootQuery and Mutation definitions have a minor syntax issue where the object returned by the fields arrow function isn't properly closed. Make sure each object is wrapped correctly:
Corrected RootQuery:
const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: () => ({ getAllUsers: { type: new GraphQLList(userType), resolve(parent, args) { return users; } } }) // This closes the object returned by fields });
Corrected Mutation:
const Mutation = new GraphQLObjectType({ name: "Mutation", // It's a good practice to capitalize type names fields: () => ({ createUser: { type: userType, args: { email: { type: GraphQLString }, username: { type: GraphQLString }, name: { type: GraphQLString }, company: { type: GraphQLString }, address: { type: GraphQLString }, }, resolve(parent, args) { const newUser = { email: args.email, username: args.username, name: args.name, company: args.company, address: args.address }; users.push(newUser); return newUser; } } }) // Close the fields object here });
3. Test Your Fixed Service
Restart your Express server, then head back to localhost:5000/graphql—you should see the GraphiQL interface now!
Try running this query to fetch all users:
query { getAllUsers { name username email } }
And test the mutation to create a user:
mutation { createUser( email: "test@example.com", username: "testuser", name: "Test User", company: "Test Corp", address: "123 Test St" ) { name username } }
内容的提问来源于stack exchange,提问作者Hassan Aref

