I am learning GraphQL and am new to the technology. I am unable to figure out the cause for this syntax error. When I am testing it on graphiql it throws an unexpected token syntax error
Here is my server.js:
const express = require("express");
const graphqlHTTP = require("express-graphql");
const schema = require("./schema");
const app = express();
app.get(
"/graphql",
graphqlHTTP({
schema: schema,
graphiql: true
})
);
app.listen(4000, () => {
console.log("Server listening to port 4000...");
});
Here is my schema:
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema,
GraphQLList,
GraphQLNotNull
} = require("graphql");
// HARD CODED DATA
const customers = [
{ id: "1", name: "John Doe", email: "jdoe@gmail.com", age: 35 },
{ id: "2", name: "Kelly James", email: "kellyjames@gmail.com", age: 28 },
{ id: "3", name: "Skinny Pete", email: "skinnypete@gmail.com", age: 31 }
];
// CUSTOMER TYPE
const CustomerType = new GraphQLObjectType({
name: "Customer",
fields: () => ({
id: { type: GraphQLString },
name: { type: GraphQLString },
email: { type: GraphQLString },
age: { type: GraphQLInt }
})
});
// ROOT QUERY
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
customer: {
type: CustomerType,
args: {
id: { type: GraphQLString }
},
resolve(parentValue, args) {
for (let i = 0; i < customers.length; i++) {
if (customers[i].id == args.id) {
return customers[i];
}
}
}
},
customers: {
type: new GraphQLList(CustomerType),
resolve(parentValue, args) {
return customers;
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
Can someone point me in the right direction? I can't figure out the problem here?
As per the documentation for express-middleware
, you should mount the middleware using app.use
, as opposed to app.get
:
app.use('/graphql', graphqlHTTP({schema, graphiql: true}))
Doing so will make the GraphiQL available in the browser, but will also allow you to make POST
requests to the /graphql
endpoint. By using app.get
, you're able to get to the GraphiQL interface, but are unable to actually make the POST
requests. When you make a request in GraphiQL, it tries to make a POST
request to your endpoint, but because your app is not configured to receive it, the request fails. The error you're seeing is the result of trying to parse the generic error express throws for a missing route into JSON.