Ajax request path problem of file Protocol for electron Packaging

use electron, to package projects into offline applications. Use the file protocol to read static resources locally. However, if the ajax request uses a relative path, after packaging, it will go directly to the root directory.

 // main.js
 const winURL = process.env.NODE_ENV === "development"
  ? `http://localhost:8080`
  : `file://${__dirname}/index.html`
  mainWindow.loadURL(winURL)

 // api.js 
  export function loginByUsername(username, password) {
  const data = {
    username,
    password
  }
  return request({
    url: "/ntwechat/login/login",
    method: "get",
    params: {
      name: username,
      password: password
    }
  })
}

at this time, the request url of network is file:/D:/ntwechat/login/login?name=nt&password
. You need to provide ajax with a complete url path, such as http: www.xxx.com/ntwechat/login/login ,
but this is too much work. I want to know if electron intercepts url.
found electron"s session module by searching

const {session} = require("electron")
session.defaultSession.webRequest.onBeforeRequest(filter, (details, callback) => {
   
    details.url = details.url.replace(/.*\/ntwechat\//ig, "http://localhost:8080/ntwechat/")

    callback({cancel: false, url: details.url});
  })

but I still can"t change the request url of the request

is there any way to solve this problem easily?

Mar.12,2021

change router- > mode:'hash',. Try it. This is how I solved it.


Brother, do you have a solution?


the same problem. How did the landlord finally solve the problem


you can use ajaxsetup for path substitution

$.ajaxSetup({
  beforeSend: function(jqXHR, settings) {
    settings.url = window.AJAXURL + settings.url.replace(/^\//, '');
  },
})

window.AJAXURL is your real request address


my project has also encountered this problem. If you go to vuex, you will have this problem, but you will not have this problem directly through the axios request.

image.png


image.png

is configured to install tutorials on the Internet.

have you solved it? I use electron-vue

Menu