App:// is where Electron and Vue API requests converge

Recently, I successfully integrated Electron into my Vue app with the help of the Vue CLI Plugin Electron Builder. During development, all API requests were properly directed to the address specified in my vue.config.js:

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

For instance, when I made an Axios POST request to /api/open_session/, it was correctly sent to http://my-api/api/open_session.

However, upon building the project, a unique app:// protocol was generated to open the index.html file. This protocol also applied to all URLs starting with app://, including API requests.

In my background.js, the logic for loading the URL differed based on the environment:

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');
}

My primary concern is to ensure that these URL paths are directed to my API, while still allowing all my files to be accessed as usual via the app protocol.

Answer №1

It's been quite a while since I faced this issue and had to find a solution independently. But here's a helpful suggestion I stumbled upon in some online forums for those struggling with the same problem:

Initially, I made adjustments to my vue.config.js:

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

Next, I updated my main.js file to include 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
})
})

which defines the application's behavior during request calls. I also added a session value to webPreferences:

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

Lastly, I loaded my index.html using the app protocol

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

As a result, all my requests were successfully redirected to my server.

If the original source of this code is identifiable, apologies for not crediting properly - feel free to add your attribution in the comments :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with child prop not being updated despite changes in parent component

I'm facing a strange issue where altering a child component's prop doesn't trigger a re-render. Here's the scenario: In the parent component, I have: <child :problemProp="proplemPropValue"></child> In the child component, ...

Retrieve the content of a file and convert it into JSON or GeoJSON format

Can someone help me with my issue? I am struggling to extract content from geojson files and assign it to a valid variable. Here is what I've tested: //this works var obj_valid = {"type": "FeatureCollection","crs": { "type": "name", "properties": { ...

Utilizing SVG elements for interactive tooltips

Can the < use > element show the rect tooltip on mouseover in modern browsers? Refer to 15.2.1 The hint element. <svg id="schematic" version="1.2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <symbol i ...

Locate the row just before the last one in the table

I have a table that dynamically creates rows, and I need to locate the second to last row in the table. HTML Code <table class="table"> <tr><td>1</td></tr> <tr><td>2</td>< ...

Navigating poorly structured HTML tables using jQuery code loops

I am currently working on a project that involves an HTML table generated by my client, and it seems like we are both in agreement not to change how the code is generated at this time. <TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0> <TR HEIG ...

What exactly is the concept of lazily installing a dependency?

The website here contains information about the changes in Ember 2.11. Ember 2.11 now utilizes the ember-source module instead of the ember Bower package. In the upcoming Ember CLI 2.12 release, Bower will no longer be installed by default but will only ...

Tips for utilizing jQuery to identify an image that is being hovered on?

Concept My goal is to create an effect where a user hovers over an image and a transparent overlay div appears on top of it. This overlay div starts with a height of 0px and should increase to half of the image height upon hover. The hover functionality ...

ExpressJS route encountering issues with GET method functionality

I'm facing an issue with my code where the function is not running inside the specific routing when trying to retrieve data using /:user. Can someone help me identify the mistake in the following implementation? const express = requi ...

A step-by-step guide on modifying the box-shadow color using jquery

I have developed some JavaScript code that adjusts the box-shadow of buttons to be a darker version of their background color. This allows users to dynamically change the button background colors. The current code successfully changes the box shadow based ...

Using JavaScript build-in functions in a Vue template allows for enhanced functionality and

Is there a way to utilize JavaScript built-in functions within a Vue template? {{ eval(item.value.substring(2)) }} I attempted to use the JS function eval() in {{}}, but encountered several errors such as: [Vue warn]: Property or method "eval" i ...

What steps can be taken to address the issue of the body-parser module being disabled in a node

My API is not functioning properly and I have observed that the body-parser module seems to be disabled in some way. Despite my efforts, I have been unable to find any information on this issue. Please refer to the image attached below for further details. ...

Moving a DOM element within AngularJS to a new location

I have created an angular directive that functions like a carousel. To keep the dom element count low, I delete elements from the dom and then re-insert them using angular.element to select, remove, and insert items as shown below: app.directive('myD ...

Display the returned view following an AJAX request

Currently, I am trying to search for a specific date in the database using ajax to trigger the function. However, I am encountering a 404 error when I should be receiving the desired outcome, and the ajax call is entering an error mode. Here is the snippet ...

Revamping the User Experience for Amazon Fire TV App

I've been working on creating a 3D application for the Amazon Fire TV using HTML5. I successfully developed and loaded it onto my Fire TV stick using the web app tester tool. Below is snippet of my code: #right{ width: 50%; display: inline-bl ...

Is it permissible to make alterations to npm modules for node.js and then share them publicly?

I have made modifications to a module called scribe.js that I use in my own module, which is published on npm. Instead of using the original module as a dependency for my module, I would like to include my modified version. I am unsure about the legal impl ...

How to hide offcanvas navigation bar with one click in Bootstrap 5

There was an issue with a Bootstrap 5 project where the offcanvas menu would remain open after clicking on an anchor link. Is there a way to automatically close the offcanvas menu after clicking on an anchor link? <nav class="navbar fixed-top py ...

Accessing JavaScript cookie within .htaccess file to establish redirection parameters according to cookie content

Is there a way to modify the rules within my .htaccess file so that it can properly read a user-side cookie and redirect based on its content? The scenario is this: I have a cookie called userstate which contains an abbreviation of US states, such as AL ( ...

Differences between Global and Local Variables in Middleware Development

While exploring ways to manage globally used data in my research, I stumbled upon this question: See 2. Answer After integrating the suggested approach into my codebase, I encountered a problem that I would like to discuss and seek help for. I created a ...

Error: The server instance pool has been terminated, requiring enhancements to the existing solution

I'm facing an issue where removing the client.close() seems to solve the problem, but I can't leave connections open to the database after the function is done. It doesn't feel secure to me. Even though the initial write completes successful ...

changing the elements' classes by using a carousel

Having trouble with a custom carousel and unable to use the standard Bootstrap carousel. This is how my code is structured: Images: <img src="1.img"/> <img src="2.img"/> <img src="3.img"/> Prev / Next buttons: <div class="left ...