目前,我正在开发一个通过API提供数据的电子应用程序。呈现器调用一个“后端函数”,该函数首先通过Keytar获取API键,然后通过axios执行API调用。
这里的问题是Keytar总是返回空/未定义的,即使具有相同功能的类似函数工作没有任何问题,这也是因为只有在存储了有效的API密钥并将由Keytar查询的情况下才能达到这一点。
我是新来的异步/等待-函数,也许我没有得到什么。
顺便说一句:也许这个头衔不太合适,但我对这个有点不知所措。
(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');
}提前谢谢。
发布于 2020-08-16 01:55:57
在return()中缺少了重要的MakeCall。
尝试:
function makeCall(method_type, url_path, data_array) {
// return this promise to MakeCall
return keytar.getPassword(keytarService, username).then((apiKey) => {
if (apiKey == null || apiKey == undefined) {
return false;
}
// return this promise to keytar.getPassword then()
return 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;
}
);
});
}https://stackoverflow.com/questions/63432274
复制相似问题