[英]uncaught ReferenceError: require is not defined in ElectronJS using example docs
[英]Uncaught ReferenceError: require is not defined Electronjs
我創建了小型 electronjs 應用程序。 只是我想獲取 API 數據,現在顯示錯誤
未捕獲的 ReferenceError:未定義要求
在 index.html 文件中,還嘗試了更多參考我無法解決這個問題我缺少什么,請你解決這個問題,並在下面附上我的代碼。
main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
function createWindow () {
const win = new BrowserWindow({
width: 1000,
height: 600,
webPreferences: {
nodeIntegration: false
}
})
// document.getElementById('heading').innerHTML="Welcome to sample page";
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
索引.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
<link rel="stylesheet" href="assets/bootstrap.min.css">
<script src="assets/jquery.min.js"></script>
<script src="assets/bootstrap.min.js"></script>
</head>
<body>
<div id="heading"></div>
<h1>Welcome to Electron Form</h1>
<script >
const electron = require('electron');
// Importing the net Module from electron remote
const net = electron.remote.net;
var post = document.getElementById('btn1');
post.addEventListener('click', () => {
var body = JSON.stringify({ key: 1 });
const request = net.request({
method: 'GET',
protocol: 'https:',
hostname: '127.0.0.1',
path: 'https://127.0.0.1/blog/wp-json/wp/v2/posts',
redirect: 'follow'
});
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
});
});
request.on('finish', () => {
console.log('Request is Finished')
});
request.on('abort', () => {
console.log('Request is Aborted')
});
request.on('error', (error) => {
console.log(`ERROR: ${JSON.stringify(error)}`)
});
request.on('close', (error) => {
console.log('Last Transaction has occurred')
});
request.setHeader('Content-Type', 'application/json');
request.write(body, 'utf-8');
request.end();
});
</script>
</body>
</html>
您需要將nodeIntegration
為 true 才能在 Render 進程中訪問 nodeJS 資源。
const win = new BrowserWindow({
width: 1000,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
或者更安全(也更復雜),避免 XSS、RCE。 您可以使用預加載腳本訪問 NodeJS 功能,並通過contextBridge API 公開自定義 API 以遠程加載內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.