SyntaxError: Unexpected token < in JSON at position 0 when testing in Graphiql

Vis*_*kur 3 graphql express-graphql

我正在学习 GraphQL 并且是该技术的新手。我无法找出此语法错误的原因。当我在 graphiql 上对其进行测试时,它会引发意外的令牌语法错误

这是我的 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...");
});
Run Code Online (Sandbox Code Playgroud)

这是我的架构:

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
});
Run Code Online (Sandbox Code Playgroud)

有人可以指出我正确的方向吗?我无法弄清楚这里的问题?

Dan*_*den 6

根据 的文档express-middleware,您应该使用 挂载中间件app.use,而不是app.get

app.use('/graphql', graphqlHTTP({schema, graphiql: true}))
Run Code Online (Sandbox Code Playgroud)

这样做将使 GraphiQL 在浏览器中可用,但也允许您向端点发出POST请求/graphql。通过使用app.get,您可以访问 GraphiQL 界面,但无法实际发出POST请求。当您在 GraphiQL 中发出请求时,它会尝试向POST您的端点发出请求,但由于您的应用程序未配置为接收它,因此请求失败。您看到的错误是尝试将通用错误表达抛出的缺失路由解析为 JSON 的结果。