Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请教一下,electron中请求接口数据应该怎么写? #67

Closed
yzqdev opened this issue Mar 2, 2022 · 6 comments
Closed

请教一下,electron中请求接口数据应该怎么写? #67

yzqdev opened this issue Mar 2, 2022 · 6 comments

Comments

@yzqdev
Copy link

yzqdev commented Mar 2, 2022

有三种方案,不知道大佬推荐用哪一种

preload中使用contextBridge,然后传递给渲染进程

使用netapi,request库或者fetch

//使用fetch,然后渲染进程使用window.getData.request(url);
contextBridge.exposeInMainWorld("getData", {
  async request(url: RequestInfo, init: RequestInit) {
    const res = await fetch(url, init);
    return await res.json();
  },
});

//使用electron的netapi
 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 the response.')
    })
  })

  request.end()

渲染进程使用类似axios,fetch的请求库

这个方法会有跨域的问题

onMounted(() => {
  fetch('http://api.com/get').then((json) => {
    return json.json();
  }).then((data ) => {
    handle(data)
  })
})

使用ipc通信

//在主线程
ipcMain.handle('FETCH_DATA', async (event, param) => {
  try {
    if (param === 'proxy') {
      await fetchDataByProxy()
    } else {
      await fetchData(param)
    }
    return {
      dataMap,
      current: config.current
    }
  } catch (e) {
    sendMsg(e, 'ERROR')
    console.error(e)
  }
  return false
})
//渲染进程
	const fetchData = async (url) => {
  state.status = 'loading'
  const data = await ipcRenderer.invoke('FETCH_DATA', url)
  if (data) {
    state.dataMap = data.dataMap
    state.current = data.current
    state.status = 'loaded'
  } else {
    state.status = 'failed'
  }
}

我现在用的第一种方法,不知道大佬推荐用哪一种方法?也许可以在模板里写个例子?

@caoxiemeihao
Copy link
Member

caoxiemeihao commented Mar 2, 2022

没有跨域的,用 axios 或 fetch 在渲染进程中写
有跨域的,用 axios 或 node-fetch 在主进程中写

@yzqdev
Copy link
Author

yzqdev commented Mar 2, 2022

好的,感谢大佬解答

@yzqdev yzqdev closed this as completed Mar 2, 2022
@k1ngbanana
Copy link

有三种方案,不知道大佬推荐用哪一种

preload中使用contextBridge,然后传递给渲染进程

使用netapi,request库或者fetch

//使用fetch,然后渲染进程使用window.getData.request(url);
contextBridge.exposeInMainWorld("getData", {
  async request(url: RequestInfo, init: RequestInit) {
    const res = await fetch(url, init);
    return await res.json();
  },
});

想请教一下你的contextBridge.exposeInMainWorld是写在preload.ts文件里面吗?然后怎么预加载的.我用用下面的方式加载不了preload文件里面的代码。

want to know where your contextBridge.exposeInMainWorld save. is it in preload.ts file? then how to preload it, i use the way below, but it doesn't load it actually.

const createWindow = () => {
  const win = new BrowserWindow({
    width: 1600,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      preload: 'electron/preload.ts', // path.join(__dirname, 'preload.js') <- not build in dist, so failed too.
    },
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL);
  } else {
    // load your file
    win.loadFile(path.join(__dirname, "../dist/index.html"));
  }

  win.webContents.openDevTools();
};

@caoxiemeihao
Copy link
Member

使用 contextBridge.exposeInMainWorld 需要关闭 nodeIntegration

@k1ngbanana
Copy link

使用 contextBridge.exposeInMainWorld 需要关闭 nodeIntegration

关闭了之后要怎么preload那个文件..我那个preload的地址一直加载不成功。然后暴露不了自定义的api

@caoxiemeihao
Copy link
Member

Demo 不可能加载不到 preload 你还是改了什么东西。去看下实际生成的文件,这个问题不难多自己研究研究。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants