我正在开发一个 Electron.js 应用程序,并尝试使用 ipcMain 和 ipcRenderer 将令牌从主进程传递到渲染器进程。但是,当我尝试在渲染器中记录接收到的数据时,它会记录未定义的数据。
ipcMain.on(IPC_ACTIONS.RECEIVE_TOKEN, async (event) => {
if (mainWindow) {
try {
const response = await fetch("http://example.com/generate-token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const data: { token?: string } = await response.json();
console.log("API response in main process:", data);
correctly, e.g., { token: "your-token-here" }
if (data && data.token) {
event.reply(IPC_ACTIONS.RECEIVE_TOKEN, { token: data.token });
} else {
event.reply(IPC_ACTIONS.RECEIVE_TOKEN, { error: "Token not received from the server" });
}
} catch (error) {
console.error("Error during API call:", error);
event.reply(IPC_ACTIONS.RECEIVE_TOKEN, { error: error.message });
}
}
});
const ipcRenderer = (window as any).ipcRenderer;
const navigate = useNavigate();
ipcRenderer.on(IPC_ACTIONS.RECEIVE_TOKEN, (event: any, payload: any) => {
console.log("Full payload received from main process:", payload);
if (payload && payload.token) {
console.log("Token received in renderer:", payload.token);
} else if (payload && payload.error) {
console.error("Error received:", payload.error);
} else {
console.error("Unexpected response received from main process:", payload);
}
});
const handleButtonClick = () => {
ipcRenderer.send(IPC_ACTIONS.RECEIVE_TOKEN);
};
即使 console.log("主进程中的 API 响应:", data);在主进程中打印一个有效的令牌(例如,{ token: "your-token-here" }),console.log("从主进程收到的完整有效负载:",payload);在渲染器进程中记录未定义
您应该发送请求而不是接收它。
const handleButtonClick = () => {
ipcRenderer.send(IPC_ACTIONS.REQUEST_TOKEN); // Change to REQUEST_TOKEN
};
IPC_ACTIONS.REQUEST_TOKEN
用于向主进程请求令牌并监听IPC_ACTIONS.RECEIVE_TOKEN
以接收令牌或错误。