【问题标题】:Cannot read property 'request' of undefined electron.js无法读取未定义 electron.js 的属性“请求”
【发布时间】:2021-08-23 08:06:42
【问题描述】:

我正在尝试让我的电子应用程序向网站发送请求,大概是在渲染器线程上。我尝试按照docs itself 上的代码进行操作,但似乎遇到了以下错误:Cannot read property 'request' of undefined

这是代码:

  const { app } = require('electron')
  const { net } = require('electron')
  const request = net.request('https://github.com')
  request.on('response', (response) => {
    console.log(`STATUS: ${response.statusCode}`)
    console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
    response.on('data', (chunk) => {
      console.log(`BODY: ${chunk}`)
    })
    response.on('end', () => {
      console.log('No more data in response.')
    })
  })
  request.end()

【问题讨论】:

  • app.whenReady().then(() => {。你错过了这条线。
  • net 是一个仅限主进程的 API,您正在尝试在渲染器进程 (index.html) 中使用它,这不受支持,也不会受到支持。在渲染器进程中使用 fetch 代替

标签: javascript electron


【解决方案1】:

我遇到了同样的问题,当我尝试从渲染器进程中使用 net 时,我得到了完全相同的错误消息,所以我假设你也这样做了。作为电子 GitHub 问题页面的引用:https://github.com/electron/electron/issues/25384

net 是唯一的主进程 API,您正在尝试在 渲染器进程 (index.html) 不支持,也不会支持。 在渲染器进程中使用 fetch 代替

fetch的用法示例:

fetch('https://github.com/')
                .then(res => res.text())
                .then(body => console.log(body))

附言。 您可能也像我一样对内容安全策略有疑问。在这种情况下,另一个答案会有所帮助:Refused to load the script because it violates the following Content Security Policy directive: "style-src 'self' 'unsafe-inline'

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2017-04-06
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多