Search code examples
javascriptvue.jselectronvue-clielectron-builder

Electron + Vue API requests fall to app://


I've built a Vue app and added Electron to it. I used Vue CLI Plugin Electron Builder

It's ok in development mode, all API requests fall on address which is written in my vue.config.js:

proxy: {
        '^/api': {
            target: 'http://my-api:3000',
            changeOrigin: true
        },
    },

For example, Axios POST request /api/open_session/ falls to http://my-api/api/open_session as needed.

When I build the project it creates an app:// protocol to open the index.html file.

But it also makes all url paths beginning with app:// including API requests.

My background.js:

if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} 
else {
createProtocol('app');
// Load the index.html when not in development
win.loadURL('app://./index.html');
}

I want these paths to be directed to my API, while open all my files as usual (via app protocol)


Solution

  • Well, it's been a longer time and I coped with that on my own. However, here's an answer I came across some forums for those who are struggling with the same issue:

    Firstly, I modified my vue.config.js:

    proxy: {
            '^/api': {
                target: 'http://127.0.0.1:3000',
                changeOrigin: true
            },
        },
    

    Then, I made some changes in main.js - added a session variable:

    const sesh = session.defaultSession.webRequest.onBeforeSendHeaders({
     urls: ['*://*/*']
    }, (details, callback) => {
    // eslint-disable-next-line prefer-destructuring
    details.requestHeaders.Host = details.url.split('://')[1].split('/')[0]
    callback({
      requestHeaders: details.requestHeaders
    })
    })
    

    that defines app's behavior when requests get called. Also, I've added a session value to webPreferences:

    const win = new BrowserWindow({
     width: 1500,
     height: 700,
     title: "Title",
     webPreferences: {
       session: sesh,
       nodeIntegration: true,
       webSecurity: false
     }
    })
    

    And, finally, load my index.html via app protocol

    createProtocol('app');
    win.loadURL('app://./index.html');
    

    In result, all my requests got redirected to my server.

    Forgive me for not knowing the source, if the author of the code is reading this, you can surely mark yourself in comments :)