首页 > 解决方案 > 无法读取未定义的属性“获取”

问题描述

我正在尝试将 REST 数据源添加到我的 Apollo 服务器。我创建了一个扩展 RESTDataSource 的类,其中包含所有 API 请求。当尝试从我的 GraphQL 解析器代码调用登录方法时,会引发错误

我怎样才能解决这个问题?

我已经尝试过:在 API 类构造函数中绑定 login 和 fetch 方法

this.login = this.login.bind(this); this.fetch = this.fetch.bind(this);

从构造函数调用登录方法

RESTDataSource 类

class API extends RESTDataSource {
        constructor() {
            super();
            this.baseURL = URL;

            this.login = this.login.bind(this);
            this.fetch = this.fetch.bind(this);
            console.log(this.fetch);
            console.log(this.login);

        }
        initialize(config) {
            //config can store different information
            //the current user can be stored in config.context for easy  access
            this.context = config.context;

        }

        async login(username, password) {
            return this.post(`/`, {
                "id": 1
            }, {
                "method": "authenticate"
            }, {
                params: {
                    "user": username,
                    "password": password
                },
                "jsonrpc": "2.0"
            })
        }
    }

这是 index.js apollo 服务器的“设置”文件:

const server = new ApolloServer({
    typeDefs,
    resolvers,
    dataSources: () => {
        return {
            managementDatabase: new ManagementDatabase(),
            API: new API() //was previously imported
        }
    }
});




server.listen().then(({
    url
}) => {
    log(`  Server ready at ${url}`)
})

GraphQL 的解析器文件:

Query: {
        lessons: async (_source, _args, {
            dataSources
        }) => {
            const data = await dataSources.webuntisAPI.login(process.env.USER, process.env.PW);
            console.log(data);
            return data;
        }
}

标签: javascriptnode.jsgraphqlapollo-server

解决方案


解决了这个问题。问题是initalize(config)在这种情况下不需要的方法。所以要解决这个问题,只需从代码中删除 initalize 方法


推荐阅读