【问题标题】:express + express-graphql helloworld returns nullexpress + express-graphql helloworld 返回 null
【发布时间】:2020-08-07 21:15:06
【问题描述】:

我是 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 解决这个问题。提前致谢。

【问题讨论】:

    标签: null graphql sequelize.js express-graphql


    【解决方案1】:

    这个

    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 或其他),您都应该使用 never use buildSchema

    【讨论】:

    • 感谢您的及时解决,然后我可以使用什么来代替 buildSchema?另外,由于我没有父对象,如何访问当前节点的父对象?
    • 哦,糟糕,您提供了解释的链接。让我经历一下。谢谢
    猜你喜欢
    • 2021-11-03
    • 2023-03-20
    • 2017-10-20
    • 2022-10-04
    • 2021-03-17
    • 2021-10-07
    • 2019-03-08
    • 2020-04-05
    • 2022-11-01
    相关资源
    最近更新 更多