Electron - #006 后端node调用http请求给前端显示

后端node调用http请求给前端显示

1 目标

后端node调用http请求给前端显示。

2 步骤

2.1 src-electron/main.js

/*
 * @Author: alan.lau
 * @Date: 2024-09-08 20:35:17
 * @LastEditTime: 2024-09-10 22:07:04
 * @LastEditors: alan.lau
 * @Description:
 * @FilePath: \electron-demo\src-electron\main.js
 * 可以输入预定的版权声明、个性签名、空行等
 */
const { app, BrowserWindow, ipcMain,dialog } = require("electron");
const { join } = require("path");
const fs = require("fs");
const path = require("path");
const axios = require("axios");

// 屏蔽安全警告
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

// 创建浏览器窗口时,调用这个函数。
const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true, // 使渲染进程拥有node环境
      //关闭web权限检查,允许跨域
      webSecurity: false,
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      preload: path.join(__dirname, "preload.js"), // 这里是预加载脚本的位置
    },
  });

  // win.loadURL('http://localhost:3000')
  // development模式
  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL);
    // 开启调试台
    win.webContents.openDevTools();
  } else {
    win.loadFile(join(__dirname, "../dist/index.html"));
  }
};

// Electron 会在初始化后并准备
app.whenReady().then(() => {
  createWindow();
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});

// 监听从渲染进程发来的 'read-file' 请求,并读取文件
ipcMain.handle('read-file', async (event, filePath) => {
    try {
        const data = fs.readFileSync(filePath, 'utf-8');
        return data;  // 返回文件内容
    } catch (error) {
        console.error('读取文件失败:', error);
        return null;
    }
});

// 主进程中添加 IPC 事件处理器,打开文件对话框并返回选中文件路径
// 处理打开文件对话框
ipcMain.handle("open-file-dialog", async () => {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    properties: ["openFile"],
  });
  if (canceled) {
    return null;
  } else {
    return filePaths[0]; // 返回文件路径
  }
});

// GET 请求示例
ipcMain.handle("get-data", async () => {
  try {
    const response = await axios.get("https://jsonplaceholder.typicode.com/posts/1");
    return response.data;
  } catch (error) {
    console.error("GET 请求错误:", error);
    return null;
  }
});

// POST 请求示例
ipcMain.handle("post-data", async (event, postData) => {
  try {
    const response = await axios.post("https://jsonplaceholder.typicode.com/posts", postData);
    return response.data;
  } catch (error) {
    console.error("POST 请求错误:", error);
    return null;
  }
});

2.2 src-electron/preload.js

const { contextBridge, ipcRenderer } = require("electron");

contextBridge.exposeInMainWorld("electronAPI", {
  readFile: (filePath) => ipcRenderer.invoke("read-file", filePath),
  openFileDialog: () => ipcRenderer.invoke("open-file-dialog"), // 确保暴露的方法名称与前端一致
  getData: () => ipcRenderer.invoke("get-data"),
  postData: (data) => ipcRenderer.invoke("post-data", data),
});

2.3 HelloWorld.vue

<!--
 * @Author: alan.lau
 * @Date: 2024-09-08 20:04:38
 * @LastEditTime: 2024-09-10 22:05:38
 * @LastEditors: alan.lau
 * @Description: 
 * @FilePath: \electron-demo\src\components\HelloWorld.vue
 * 可以输入预定的版权声明、个性签名、空行等
-->
<script setup lang="ts">
import { ref, onMounted } from "vue";
import * as Cesium from 'cesium';

defineProps<{ msg: string }>()

const count = ref(0)
var viewer: Cesium.Viewer | null = null;
const filePath = ref<string | null>(null);
const fileContent = ref<string | null>(null);
onMounted(() => {
  viewer = new Cesium.Viewer('cesiumContainer', {
    terrain: Cesium.Terrain.fromWorldTerrain(), // 地形数据
  });
});

const handleReadFileFromNode = async () => {
  const content = await window.electronAPI.readFile('D:\\work\\111.txt');  // 读取文件内容
  console.log(content)

};

const handleSelectFile = async () => {
  const path = await (window as any).electronAPI.openFileDialog();
  if (path) {
    filePath.value = path;

    // 可选:读取文件内容
    const content = await (window as any).electronAPI.readFile(path);
    fileContent.value = content;
  }
};

const getResult = ref(null);
const postResult = ref(null);

const fetchData = async () => {
  getResult.value = await window.electronAPI.getData();  // 调用后端的 GET 请求
};

const sendData = async () => {
  const postData = { title: 'foo', body: 'bar', userId: 1 };  // 模拟 POST 数据
  postResult.value = await window.electronAPI.postData(postData);  // 调用后端的 POST 请求
};
</script>

<template>
  <el-button type="primary" @click="fetchData">获取数据 (GET)</el-button>
  <el-button type="primary" @click="sendData">发送数据 (POST)</el-button>

  <p>GET 请求结果: {{ getResult }}</p>
  <p>POST 请求结果: {{ postResult }}</p>
  <el-button type="primary" @click="handleSelectFile">选择文件</el-button>
  <p>选中文件路径: {{ filePath }}</p>
  <p>文件内容:</p>
  <pre>{{ fileContent }}</pre>
  <h1>{{ msg }}</h1>
  <el-button type="primary" @click="handleReadFileFromNode">我是 ElButton</el-button>

  <el-container class="home-container">
    <el-header>
    </el-header>
    <el-main>
      <div id="cesiumContainer">
      </div>
    </el-main>
  </el-container>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>

2.4 运行工程

  npm run dev

看到一下界面说明成功

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用electron-edge-js库调用C程序需要进行以下步骤: 1. 安装electron-edge-js库:可以通过npm install electron-edge-js命令来安装electron-edge-js库。 2. 在Electron的渲染进程中引入electron-edge-js库:可以使用require函数将electron-edge-js库引入到Electron的渲染进程文件中。 3. 准备C函数:在C文件中定义需要调用的函数。 4. 编译C代码:使用C编译器将C代码编译成可执行文件(如Windows平台的.exe文件、Mac平台的.dylib文件等)。 5. 创建配置文件:创建一个userconfig文件,该文件用于配置C函数的名称和所对应的dll文件路径或so文件路径等。 6. 在Electron的渲染进程中调用C函数:使用electron-edge-js库的func函数和userconfig配置文件中定义的函数名称来调用C函数。 下面是一个简单的例子: ```javascript // 引入electron-edge-js库 const edge = require('electron-edge-js'); // 创建配置文件 const userConfig = { assemblyFile: 'path/to/your/dll/file', typeName: 'NameSpace.ClassName', methodName: 'FunctionName' }; // 调用C函数 const cFunc = edge.func(userConfig); cFunc(parameters, (error, result) => { if (error) { // 处理错误 console.error(error); } else { // 处理结果 console.log(result); } }); ``` 在这个例子中,我们首先引入electron-edge-js库,然后创建一个userconfig配置文件,并定义要调用的C函数的相关信息。之后,使用electron-edge-js库的func函数来调用C函数,并传入参数。最后,处理C函数的返回结果或错误信息。 需要注意的是,具体的操作步骤和配置文件的内容可能会因为不同的C程序和操作系统而有所差异,需要根据实际情况进行适当的调整。以上只是一个简单的示例,提供了使用electron-edge-js库调用C程序的基本思路。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

满天飞飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值