javascript - 无法读取未定义的属性“获取”
问题描述
我正在尝试将 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;
}
}
解决方案
解决了这个问题。问题是initalize(config)
在这种情况下不需要的方法。所以要解决这个问题,只需从代码中删除 initalize 方法
推荐阅读
- sql - SSRS 报告表达式
- xml - 在 Powershell 中从 XML 中获取数据 - Xpath 用法
- javascript - ajax 发布在 chrome 上工作,但在 firefox 和 safari 上不工作
- jquery - 我应该如何在 jQuery 中从 JSON 中获取数据?
- android - 从后台服务启动一个活动并等待它被创建
- laravel-nova - Laravel Nova 从 HasMany 字段中隐藏视图按钮
- ios - 不支持指定的色彩空间格式。回到libyuv
- javascript - 为什么 setInterval 对 XSS 不安全?
- python-3.x - 在 Matplotlib 中循环更新 Poly3DCollection 的颜色
- java - 本地到 GMT,反之亦然 - 日期和时间转换不起作用