'Electron - data from external API being passed to Vue renderer disappears
I'm building an app using Electron, the Quasar UI framework, and Vue 3. The app talks to a Laravel backend using a REST API, but I've had trouble with the login process, particularly passing the data from the main process to the renderer process as it involves promises.
I'm using the @electron/remote to pass the data from the renderer process to the main process. I've set this up in the src/electron-main.js file as per this tutorial.
Here is the code that actually sends the API login request:
src-electron/electron-preload.js
import {contextBridge} from 'electron';
contextBridge.exposeInMainWorld('electronApi', {
getJwtFromServer: async (email, password, server) => {
fetch(
`https://login.${server}/api/v1.1/auth/login`, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'x-api-key': '<api key goes here>',
'Cookie': 'XDEBUG_SESSION=PHPSTORM',
},
body: new URLSearchParams({
'email': email,
'password': password
})
}).then(res => {
res.json()
.then(data => {
return data.token;
}).catch(error => {
return error.msg;
})
}).catch(error => {
return error.msg;
})
},
}
});
In the frontend, I then have an Electron API (in TypeScript) which intercepts the data from the main process and forwards it to the renderer:
src/api/electron-api.ts
export interface ElectronApi {
getJwtFromServer: (
email: string,
password: string,
server: string
) => Promise<object>;
}
export const electronApi: ElectronApi = (window as {electronApi: ElectronApi})
.electronApi;
Then in the Vue app I invoke the Electron API, which calls the function in the main process and sends a request to the backend. The correct data is returned to the backend, yet it seems to get lost before it reaches the Vue app.
LoginPage.vue
import {electronApi} from '../api/electron-api';
export default {
data() {
return {
server: '',
email: '',
password: '',
token: ''
}
},
methods: {
loginUser() {
electronApi.getJwtFromServer(this.email, this.password, this.server)
.then((res) => {
console.log("Fetched token: ", res);
this.token = res;
})
},
}
};
The console.log() in the LoginPage.vue component is always undefined. Where is the data getting lost along the way?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
