首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >express + express-graphql helloworld返回null

express + express-graphql helloworld返回null
EN

Stack Overflow用户
提问于 2020-04-24 18:11:15
回答 1查看 140关注 0票数 1

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

这是我的解析器:

代码语言:javascript
复制
module.exports = {
  Query: {
    hello: (parent, { name }, context, info) => {
      return `Hello ${name}`;
    },
  },
};

以下是我的方案:

代码语言:javascript
复制
const { buildSchema } = require("graphql");
module.exports = buildSchema(
  `type Query{
        hello(name:String!):String!
    }
    `
);

这是我的应用程序app.js的根目录。我遗漏了我禁用的中间件,因为它看起来无关紧要,因为无论有没有它们,我都会出现错误

代码语言:javascript
复制
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;

当我按如下方式查询时:

代码语言:javascript
复制
{
   hello(name: "me")
}

我得到了这个错误:

代码语言:javascript
复制
{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Query.hello.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "hello"
      ]
    }
  ],
  "data": null
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-24 18:42:09

代码语言:javascript
复制
module.exports = {
  Query: {
    hello: (parent, { name }, context, info) => {
      return `Hello ${name}`;
    },
  },
};

是一个解析器映射,就像graphql-toolsapollo-server期望得到的那样。这不是可传递给rootValue的有效对象。

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

代码语言:javascript
复制
module.exports = {
  hello: ({ name }, context, info) => {
    return `Hello ${name}`;
  },
};

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61405980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档