Electron+Vue API请求属于应用程序://



我已经构建了一个Vue应用程序并添加了Electron。我使用了Vue CLI插件Electron Builder

在开发模式下没问题,所有API请求都落在我的vue.config.js:中写的地址上

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

例如,Axios POST请求/api/open_session/根据需要变为http://my-api/api/open_session

当我构建项目时,它会创建一个app://协议来打开index.html文件。

但它也使所有以app://开头的url路径包括API请求。

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

我希望这些路径指向我的API,同时像往常一样打开我的所有文件(通过应用程序协议(

好吧,这是一段更长的时间,我自己解决了。然而,我在一些论坛上看到了一个答案,供那些正在为同一问题而挣扎的人使用:

首先,我修改了我的vue.config.js:

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

然后,我在main.js中做了一些更改——添加了一个会话变量:

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

定义调用请求时应用程序的行为。此外,我还为webPreferences:添加了一个会话值

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

最后,通过应用程序协议加载我的index.html

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

结果,我所有的请求都被重定向到了我的服务器。

请原谅我不知道来源,如果代码的作者正在阅读这篇文章,你肯定可以在评论中标记自己:(

相关内容

最新更新