Electron打包后发送http请求时丢失Cookie,后端报401未经授权错误

项目场景:

前端vue项目在dev模式下运行在localhost:8080端口时,发送的http请求可以正常携带cookie字段,但经electron打包后,在electron窗口运行时,发送同样的api请求,请求头中却没有cookie,导致flask后端报401未经授权错误,报错的api接口使用了@login_required注解。


解决方案:

在查找文档后,发现可以使用Electron的WebRequest类来为http请求头添加上cookie。我的应用在login请求登录后,会在响应头中存在set-cookie字段,因此首先获取这个set-cookie字段的值,保存在本地变量,之后再对后续需要权限验证的请求头设置上这个cookie。electron官方文档:WebRequest
/electron/main.js中整体代码如下:

const { app, BrowserWindow, session } = require('electron')
const path = require("path")

let storedCookie = ''; // 用于存储提取的 cookie

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,  // 使用 Node.js 集成  
      webSecurity: false,
      enableRemoteModule: true
    }
  })

  // 构造路径  
  const filePath = `file://${path.join(__dirname, "../dist/index.html")}`;

  mainWindow.loadURL(filePath);
  // 打开调试窗口
  // mainWindow.webContents.openDevTools();

}

app.whenReady().then(() => {
  // 登录请求路径 
  const loginFilter = {  
    urls: ['http://114.xxx.xxx.xxx:5000/auth/login'] 
  }; 
  // 监听响应并提取 Set-Cookie  
  session.defaultSession.webRequest.onCompleted(loginFilter, (details) => {  
    const setCookieHeader = details.responseHeaders['Set-Cookie'];  
    if (setCookieHeader) {  
      // 提取 cookie  
      storedCookie = setCookieHeader.join('; '); // 将多个 cookie 合并为一个字符串  
      // console.log('Stored Cookie:', storedCookie);  
    }  
  });  

  // 需要设置cookie字段的请求路径
  const requestsFilter = {  
    urls: ['http://114.xxx.xxx.xxx:5000/*']  
  }; 
  // 为需要的请求添加请求头中的cookie字段
  session.defaultSession.webRequest.onBeforeSendHeaders(requestsFilter, (details, callback) => {
    if (!details.url.includes('http://114.xxx.xxx.xxx:5000/auth/login')) {
      console.log('Request URL:', details.url); // 打印请求的 URL    
      if (storedCookie) {  
        details.requestHeaders['Cookie'] = storedCookie; // 使用提取的 cookie  
        console.log('Modified Headers:', details.requestHeaders); // 打印修改后的请求头  
      }  
    }  
    callback({ requestHeaders: details.requestHeaders })
  })

  createWindow()
})

另,因为第一次使用electron打包,在如何输出主进程调试信息这个简单问题上也摸索了很久。我使用的是ubuntu图形界面,打包后的应用是AppImage格式,直接双击应用即可启动。但是启动后的应用中devtools只能打印渲染进程的调试信息,即一些在vue文件中console.log的输出,/electron/main.js中console.log却无法输出。最后发现主进程的调试需要使用终端来打开,即在打包后的应用所在的文件中打开终端(我的文件夹是app_clients),运行./xxx.AppImage,此时在终端中即会输出主进程的打印信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值