graphql - 语法错误 : Unexpected token < in JSON at position 0 when testing in Graphiql

标签 graphql express-graphql

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

这是我的 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...");
});

这是我的架构:
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
});

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

最佳答案

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

app.use('/graphql', graphqlHTTP({schema, graphiql: true}))

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

关于graphql - 语法错误 : Unexpected token < in JSON at position 0 when testing in Graphiql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53897364/

相关文章:

django - 默认解析器的身份验证/授权

graphql - 突变方法是否需要在顶层?

express - 将获取响应 header 转发到 Apollo graphql 响应

GraphQL 部分更新响应类型

node.js - 转换为数字失败的值 - GraphQL

node.js - 如何在保持对请求对象的访问的同时对express-graphql解析器进行依赖注入(inject)?

graphql - 是否可以使用 GraphQLList 从多个表中获取数据

javascript - 如何修复数据类型关系导致的 'Variable "$_v0_data“得到无效值” - Mutation Resolver

javascript - GraphQL:不可为空的数组/列表

graphql - 如何使用 GraphQL 和 node 实现接口(interface)