英文:
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:
<!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>
This is 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; // Change the port number if needed
app.on('ready', () => {
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('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);
// You can send the API response data back to the renderer process if needed
mainWindow.webContents.send('api-response', responseData);
} catch (error) {
console.error('Error sending data to API:', error);
// Log specific error details
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()
});
and this is 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 });
});
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('/api/data', (req, res) => {
// 用你自己的逻辑替换这里获取数据的部分
const responseData = data;
res.json(responseData);
});
app.listen(appPort, () => {
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('/api/data', (req, res) => {
// Replace this with your logic to get data
const responseData = data;
res.json(responseData);
});
app.listen(appPort, () => {
console.log(`API server is running on
http://localhost:${appPort}`);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论