How to send parameters to API url in electron?

huangapple go评论59阅读模式
英文:

How to send parameters to API url in electron?

问题

我创建了一个 Electron 应用程序,但对此还不熟悉。我正在尝试使用 HTML 从用户那里获取输入。然后,我想在点击按钮后将这些输入发送到 main.js。在 main.js 中,我正在尝试使用 endpoint 发送一个端口。这是 HTML 文件:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Electron REST API</title>
</head>
<body>
  <h1>Hello from Electron!</h1>
  

  <label for="dx">dx:</label>
    <input type="number" id="dxInput"><br>

    <button id="fetchButton">Submit</button>
    <div id="dataDisplay"></div>
    
    <script src="./renderer.js"></script>
</body>
</html>

这是 main.js:

const { app, BrowserWindow,  } = require('electron');
const axios = require('axios');
const express = require('express');
const { dialog, ipcMain } = require("electron");
var http = require('http');

let mainWindow;
const appPort = 3000; // 如果需要,可以更改端口号

app.on('ready', () => {
  mainWindow = new BrowserWindow({ width: 800, height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
      
      
    }, });

    mainWindow.loadURL(`file://${__dirname}/index.html`);

  // 启动 Express.js 服务器
  const app = express(); 

ipcMain.on('fetch-data', async (event, data) => {
  const { dx} = data;

 try {
    const response = await axios.get('http://localhost:3000/api/data2', {
      params: { dx }
    });
  
    const responseData = response.data;
    console.log('Received data from API:', responseData);
  
    // 如果需要,可以将 API 响应数据发送回渲染进程
    mainWindow.webContents.send('api-response', responseData);
  } catch (error) {
    console.error('Error sending data to API:', error);
  
    // 记录特定的错误详情
    if (error.response) {
      console.error('Response Data:', error.response.data);
      console.error('Response Status:', error.response.status);
    } else if (error.request) {
      console.error('No response received:', error.request);
    } else {
      console.error('Error:', error.message);
    }
  }
  
});

mainWindow.webContents.openDevTools()
  
});

这是 renderer.js:

const { ipcRenderer } = require('electron');

const fetchButton = document.getElementById('fetchButton');
const dxInput = document.getElementById('dxInput');

fetchButton.addEventListener('click', async () => {
    const dx = parseFloat(dxInput.value);

    ipcRenderer.send('fetch-data', { dx });
});

目前,我可以从 renderer.js 将参数发送到 main.js。然而,我无法将参数发送到 API URL。当我尝试时,我得到了以下错误:

Error sending data to API: AxiosError: Request failed with status code 404

我该如何解决这个问题?

英文:

I have created an Electron app and I am new at this. I am trying to get inputs from a user using HTML. Then, I want to send these inputs to main.js after clicking the button. In main.js I am trying to send a port using endpoint. This is HTML file:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;meta charset=&quot;UTF-8&quot;&gt;
  &lt;title&gt;Electron REST API&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1&gt;Hello from Electron!&lt;/h1&gt;
  

  &lt;label for=&quot;dx&quot;&gt;dx:&lt;/label&gt;
    &lt;input type=&quot;number&quot; id=&quot;dxInput&quot;&gt;&lt;br&gt;

    &lt;button id=&quot;fetchButton&quot; &gt;Submit&lt;/button&gt;
    &lt;div id=&quot;dataDisplay&quot;&gt;&lt;/div&gt;
    
    &lt;script src=&quot;./renderer.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

This is main.js:

const { app, BrowserWindow,  } = require(&#39;electron&#39;);
const axios = require(&#39;axios&#39;);
const express = require(&#39;express&#39;);
const { dialog, ipcMain } = require(&quot;electron&quot;);
var http = require(&#39;http&#39;);

let mainWindow;
const appPort = 3000; // Change the port number if needed

app.on(&#39;ready&#39;, () =&gt; {
  mainWindow = new BrowserWindow({ width: 800, height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
      
      
    }, });

    mainWindow.loadURL(`file://${__dirname}/index.html`);

  // Start the Express.js server
  const app = express(); 

ipcMain.on(&#39;fetch-data&#39;, async (event, data) =&gt; {
  const { dx} = data;

 try {
    const response = await axios.get(&#39;http://localhost:3000/api/data2&#39;, {
      params: { dx }
    });
  
    const responseData = response.data;
    console.log(&#39;Received data from API:&#39;, responseData);
  
    // You can send the API response data back to the renderer process if needed
    mainWindow.webContents.send(&#39;api-response&#39;, responseData);
  } catch (error) {
    console.error(&#39;Error sending data to API:&#39;, error);
  
    // Log specific error details
    if (error.response) {
      console.error(&#39;Response Data:&#39;, error.response.data);
      console.error(&#39;Response Status:&#39;, error.response.status);
    } else if (error.request) {
      console.error(&#39;No response received:&#39;, error.request);
    } else {
      console.error(&#39;Error:&#39;, error.message);
    }
  }
  
});

mainWindow.webContents.openDevTools()
  
});

and this is renderer.js:

const { ipcRenderer } = require(&#39;electron&#39;);

const fetchButton = document.getElementById(&#39;fetchButton&#39;);
const dxInput = document.getElementById(&#39;dxInput&#39;);

fetchButton.addEventListener(&#39;click&#39;, async () =&gt; {
    const dx = parseFloat(dxInput.value);

    ipcRenderer.send(&#39;fetch-data&#39;, { dx });
});

For now, I can send the parameter from renderer.js to main.js. However, I can not send the parameter to API URL. When I tried this I got this error:

> Error sending data to API: AxiosError: Request failed with status code 404

How can I fix this problem?

答案1

得分: 0

最后,我解决了这个问题。

> const response = await axios.get('http://localhost:3000/api/data2', {
params: { dx }

我改用了get方法(端点)来解决这个问题。get方法修复了问题。我将代码添加到了

> ipcMain.on('fetch-data', async (event, data) => {

这个函数中。
代码如下:

app.get(&#39;/api/data&#39;, (req, res) =&gt; {
          // 用你自己的逻辑替换这里获取数据的部分
          
          const responseData = data;
          res.json(responseData);
        });
      
        app.listen(appPort, () =&gt; {
          console.log(`API 服务器正在运行,地址为 
         http://localhost:${appPort}`);
        });
英文:

Finally, I solved the problem.

> const response = await axios.get('http://localhost:3000/api/data2', {
params: { dx }

Instead of using axios.get, I used get method (endpoint) for this. And get method fixed the problem. I added the code inside

> ipcMain.on('fetch-data', async (event, data) => {

this function.
The code is:

app.get(&#39;/api/data&#39;, (req, res) =&gt; {
          // Replace this with your logic to get data
          
          const responseData = data;
          res.json(responseData);
        });
      
        app.listen(appPort, () =&gt; {
          console.log(`API server is running on 
         http://localhost:${appPort}`);
        });

huangapple
  • 本文由 发表于 2023年8月8日 22:00:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定