带有 Express(JS) 的后端 - GraphQL 变异函数不起作用

Posted

技术标签:

【中文标题】带有 Express(JS) 的后端 - GraphQL 变异函数不起作用【英文标题】:Backend with Express(JS) - GraphQL mutation function doesn't work 【发布时间】:2021-10-20 08:15:36 【问题描述】:

我没有在后端的突变 GraphQL 中获得请求变量。我不明白为什么它不起作用。 我得到下一个错误: “无法解构‘未定义’的属性‘名称’,因为它是未定义的。”

我在 Apollo Studio 中所做的突变:

mutation Mutation($createOwnerName: String) 
  createOwner(name: $createOwnerName)

我在 Apollo Studio 中的变量:


  "createOwnerName": "John"

我使用 Express 的后端 schema.js:

const  buildSchema  = require("graphql");
const schema = buildSchema(`
 type Mutation 
    createOwner(name: String): String
  
`);

module.exports = schema;

resolvers.js:

const resolvers = 
 Mutation: 
  createOwner: (name) => 
      console.log('createOwner name', name)
      return name
  
 

server.js:

const  createServer  = require("http");
const express = require("express");
const  execute, subscribe  = require("graphql");
const  ApolloServer  = require("apollo-server-express");
const  SubscriptionServer  = require("subscriptions-transport-ws");
const  makeExecutableSchema  = require("@graphql-tools/schema");
const typeDefs = require("./graphql/schema.js");
const resolvers = require("./graphql/resolvers.js");
require("dotenv").config();
const mongoose = require("mongoose");

// mongoose
mongoose
  .connect(process.env.DB_HOST, 
    useNewUrlParser: true,
    useUnifiedTopology: true,
  )
  .then(() => console.log("MongoDB connected"))
  .catch((err) => console.log(err));

(async () => 
  const PORT = 3033;
  const app = express();
  const httpServer = createServer(app);

  app.get("/rest", function (req, res) 
    return res.json( data: "rest" );
  );

  const schema = makeExecutableSchema( typeDefs, resolvers );

  const server = new ApolloServer(
    schema,
  );
  await server.start();
  server.applyMiddleware( app );

  SubscriptionServer.create(
     schema, execute, subscribe ,
     server: httpServer, path: server.graphqlPath 
  );

  httpServer.listen(PORT, () => 
    console.log(
      `???? Query endpoint ready at http://localhost:$PORT$server.graphqlPath`
    );
    console.log(
      `???? Subscription endpoint ready at ws://localhost:$PORT$server.graphqlPath`
    );
  );
)();

【问题讨论】:

【参考方案1】:

您正在解构错误的论点。参数按以下顺序排列:

父值 参数值 上下文 GraphQL 解析信息

解构第二个参数:

const resolvers = 
 Mutation: 
  createOwner: (parent, name) => 
      console.log('createOwner name', name)
      return name
  
 

【讨论】:

以上是关于带有 Express(JS) 的后端 - GraphQL 变异函数不起作用的主要内容,如果未能解决你的问题,请参考以下文章

如何使用分离的后端和前端(Passport / Express / React)进行社交身份验证

node 06

React 前端 + Express.js 会话

上传图片文件到服务器node.js express axios

在 Express 中设置默认响应标头

基于Koa2+mongoDB的后端博客框架