在 Electron 中单击时 ReactJs 无法调用 express API
Posted
技术标签:
【中文标题】在 Electron 中单击时 ReactJs 无法调用 express API【英文标题】:ReactJs not able to call the express API when click in Electron 【发布时间】:2021-10-01 06:07:27 【问题描述】:当我单击在 Electron 环境中运行的 React 中的按钮时,我试图调用 express API,但它不起作用。
我在登录功能中做了一个控制台登录,当我点击按钮时,它确实打印出了控制台中的值。
我还在用户/登录 api 上做了控制台日志,虽然它没有打印出值,但它确实打印出 MongoDB 连接成功。我想知道我错过了什么。以下是代码:
Main.js
const app, BrowserWindow,Menu, shell = require('electron')
const server = require('../../server.js')
const isDev = require('electron-is-dev')
process.env.NODE_ENV = "development"
const isMac = process.platform === "darwin" ? true : false
let mainWindow
let aboutWindow
function createMainWindow ()
mainWindow = new BrowserWindow(
width:1024,
height:768,
show: false,
backgroundColor:"#263238"
)
mainWindow.loadURL(isDev ? 'http://localhost:3000' : `file://$path.join(__dirname, '../build/index.html')`)
mainWindow.once('ready-to-show', () =>
mainWindow.show();
mainWindow.focus();
);
mainWindow.webContents.on('new-window', function(event, url)
event.preventDefault();
shell.openExternal(url);
)
app.on('ready', () =>
createMainWindow()
const mainMenu = Menu.buildFromTemplate(menu)
Menu.setApplicationMenu(mainMenu)
mainWindow.on('ready', () => mainWindow = null)
)
const menu = [
...(isMac ? [
label: 'app.name',
submenu:[
label:'About',
click: createAboutWindow
]]:[]),
role:'fileMenu'
,
...(!isMac ? [
label:'Help',
submenu:[
label:'About',
click: createAboutWindow
]
]:[]),
...(isDev ? [
label:'Developer',
submenu:[
role:'reload',
role:'forcereload',
role:'separator',
role:'toggledevtools',
]
]:[])
]
app.on('window-all-closed', function ()
if (isMac) app.quit()
)
app.whenReady().then(() =>
app.on('activate', function ()
if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
)
)
服务器.js
const express = require("express");
const app = express();
const morgan = require('morgan');
const bodyParser = require("body-parser");
const cors = require("cors");
const dotenv = require('dotenv');
const connectDB = require("./dbconfig/dbconfig");
const cookieParser = require('cookie-parser');
const path = require('path');
const userRoute = require('./routes/user')
dotenv.config()
connectDB()
const cluster = require('cluster')
const numCPUs = require('os').cpus().length
const port = process.env.PORT || 5000
var whitelist = ['http://localhost:3000', 'http://localhost:5000'];
app.use(cors( credentials: true, origin: whitelist));
app.use(cookieParser())
app.use(morgan('dev'))
app.use(bodyParser.json( limit: '50mb' ))
app.use(bodyParser.urlencoded( extended: false ))
app.use('/api', userRoute)
app.use(express.static(path.join("frontend", "build")))
app.get("*", (req, res) =>
res.sendFile(path.resolve(__dirname, "frontend", "build", "index.html"))
)
require("http").createServer(function (req, res)
console.log("Hello from server started by Electron app!");
console.log(`Listening to part $port...`)
).listen(port)
用户路线
router.post('/user/login', async (req, res) =>
console.log(req.body)
)
反应环境文件
REACT_APP_FETCH_URL=http://localhost:3000
React 登录组件
const login = async (e) =>
console.log(loginData)
setLoading(true);
e.preventDefault();
const response = await Axios.post(
process.env.REACT_APP_FETCH_URL + "/api/user/login",loginData, withCredentials: true );
if (response.data.statusCode == 200)
setLoading(false);
window.location.replace("/test");
else
setLoading(false);
;
<button type="submit" onClick=login className="btn btn-block btn-primary btn-lg font-weight-semibold auth-form-btn" disable=loading>
loading && <i className="fa fa-refresh fa-spin" ></i>
Sign In</button>
封装 JSON 代理
"name": "frontend",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:5000",
"dependencies":
"@fortawesome/fontawesome-svg-core": "^1.2.35",
"@fortawesome/free-solid-svg-icons": "^5.15.3",
"@fortawesome/react-fontawesome": "^0.1.14",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"concurrently": "^6.2.0",
"cross-env": "^7.0.3",
"electron": "^13.1.7",
"electron-builder": "^22.11.7",
"electron-is-dev": "^2.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-infinite-scroll-component": "^6.1.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"wait-on": "^6.0.0",
"web-vitals": "^1.1.2"
,
"scripts":
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"electron-serve": "concurrently \"cross-env BROWSER=none npm start\" \"wait-on http://localhost:3000 && electron .\"",
"electron-build": ""
,
"build":
,
"eslintConfig":
"extends": [
"react-app",
"react-app/jest"
]
,
"browserslist":
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
,
"main": "public/main.js",
"homepage": "./"
提前非常感谢,非常感谢任何帮助。再次感谢。
【问题讨论】:
【参考方案1】:很抱歉给您带来麻烦。在我尝试并捕获并控制台记录错误后,我现在知道是 jwt 导致了问题。
对于给您带来的不便,我深表歉意。
【讨论】:
以上是关于在 Electron 中单击时 ReactJs 无法调用 express API的主要内容,如果未能解决你的问题,请参考以下文章
我试图在 Electron.js 中单击按钮时打开新窗口,但未捕获 ReferenceError: require is not defined