【发布时间】:2020-08-16 09:55:57
【问题描述】:
目前我正在开发一个通过 API 提供数据的 Electron 应用程序。渲染器调用一个“后端函数”,它首先通过Keytar获取API密钥,然后通过axios执行API调用。
这里的问题是 Keytar 总是返回 null/undefined,即使具有相同功能的类似函数没有任何问题,也因为只有存储了有效的 API 密钥才能达到这一点,这也将被 Keytar 查询。
我是 async/await-functions 的新手,也许我没有得到什么。
顺便说一句:可能标题不太合适,但我对这个有点不知所措。
(keytarService、用户名、baseUrl 是全局变量)
这是我的代码:
// api调用函数
async function makeCall(method_type, url_path, data_array) {
keytar.getPassword(keytarService, username).then((apiKey) => {
if (apiKey == null || apiKey == undefined) {
return false;
}
axios({
method: method_type,
url: baseUrl + url_path,
headers: {
'content-type': 'application/json',
'X-AUTH-TOKEN': apiKey,
},
data: data_array,
}).then(
(response) => {
return response.data;
},
(error) => {
return false;
}
);
});
}
//index_renderer.js
webContents.on('dom-ready', () => {
apiMain
.makeCall('GET', 'user/self')
.then((data) => {
console.log(data);
document.getElementById('username_text').innerText =
data.firstName + '' + data.lastName;
})
.catch((err) => console.log(err));
});
正在运行的类似功能:
async function isAuthenticated() {
apiKey = await keytar.getPassword(keytarService, username);
if (apiKey == null || apiKey == undefined) {
return false;
}
axios({
method: 'GET',
url: baseUrl + '/api/isAuthenticated',
headers: {
'content-type': 'application/json',
'X-AUTH-TOKEN': apiKey,
},
data: {},
}).then(
(response) => {
console.log(response);
if (!response.data.authenticated) {
logout();
}
return response;
},
(error) => {
console.log(error);
logout();
return error;
}
);
}
// main.js中工作函数的调用
if (authProcess.isAuthenticated()) {
mainwin.loadFile('index.html');
} else {
mainwin.loadFile('login.html');
}
提前致谢。
【问题讨论】:
标签: javascript asynchronous async-await axios electron