express + express-graphql helloworld returns 空

express + express-graphql helloworld returns null

我是 graphql 的新手,正在尝试实现一个简单的 helloworld 解决方案,该解决方案在查询时返回 null。该设置包括 sequelize 和 pg 以及 pg-hstore,但我已将其禁用以尝试找出问题所在。提前致谢,卡了两天

这是我的解析器:

module.exports = {
  Query: {
    hello: (parent, { name }, context, info) => {
      return `Hello ${name}`;
    },
  },
};

这是我的架构:

const { buildSchema } = require("graphql");
module.exports = buildSchema(
  `type Query{
        hello(name:String!):String!
    }
    `
);

这是我的应用程序的根,app.js。我遗漏了我已禁用的中间件,因为它似乎无关紧要,因为无论有没有它们我都会出错

const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const sassMiddleware = require("node-sass-middleware");
const graphqlHTTP = require("express-graphql");
const schema = require("./persistence/graphql/schema");
const persistence = require("./persistence/sequelize/models");
const rootValue = require("./persistence/sequelize/resolvers/index");

const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");

const app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");

app.use(
  "/api/graphql",
  graphqlHTTP({
    schema,
    rootValue,
    graphiql: true,
  })
);

module.exports = app;

当我查询如下:

{
   hello(name: "me")
}

我收到这个错误:

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Query.hello.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "hello"
      ]
    }
  ],
  "data": null
}

我知道那里还有其他服务器,但我真的需要用 express-graphql 解决这个问题。提前致谢。

这个

module.exports = {
  Query: {
    hello: (parent, { name }, context, info) => {
      return `Hello ${name}`;
    },
  },
};

是一个像 graphql-toolsapollo-server 期望得到的解析器映射。这不是传递给 rootValue.

的有效对象

如果您想使用 rootValue 来解析您的根级字段,那么该对象将需要只是一个没有类型信息的字段名称映射。此外,如果您使用函数作为值,它们将只接受三个参数(args、context 和 info)。

module.exports = {
  hello: ({ name }, context, info) => {
    return `Hello ${name}`;
  },
};

也就是说,这不是一个解析器函数——通过根传递这样的值与实际为您的架构中的字段提供解析器是不同的。无论您使用的是什么 HTTP 库(express-graphql 或其他),您都应该 .