Reputation: 195
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: "[email protected]", age: 35 },
{ id: "2", name: "Kelly James", email: "[email protected]", age: 28 },
{ id: "3", name: "Skinny Pete", email: "[email protected]", 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?
Upvotes: 4
Views: 6395
Reputation: 5155
In my case this error message was caused by a stupid error, so probably my story will be useful for someone:
Instead of having JSON value with {"query":"graphqlQueryHere ..."}
I just posted the plain graphQL query instead of JSON. Please take a look that you don't do the same.
Upvotes: 0
Reputation: 84687
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.
Upvotes: 8