Eel urllib 请求函数 returns 对 JS 为 null,但值为 python

Eel urllib request function returns null to JS, but value to python

我有以下 Python 鳗鱼代码

import eel, urllib.request

@eel.expose
def python_function():
    response = urllib.request.urlopen('http://google.com').read()
    return(response)

eel.init('web')
eel.start('index.html', port=0)

现在当我用

从JavaScript调用它时
async function jsFunction() {
    let result = await eel.python_function()();

    return result;
}

我总是得到 null。当我从 Python 调用 print(python_function()) 时,我得到了预期的 HTML 字符串。

测试时,JavaScript returns 在达到 URL 之前为空。我以为 Python 阻止了代码。我需要重新实现一个块吗?从 python_function 返回字符串将得到 jsFunction.

中的实际字符串

试试这个:

@eel.expose
def python_function():
    response = urllib.request.urlopen('http://google.com').read()

    return response.decode('latin1')

区别在于response.decode('latin1') return.

在 Eel 的 Python 层中,您必须 return 一个根据 Python's JSON encoder 可序列化的对象,并且原始二进制字符串 return 由 read() 不可序列化。

看一下我提供给的答案,详细解释了EelPython和JavaScript层之间的通信要求

此外,您应该在 Python 代码中解决的另一个问题是 eel.init('web') 应该出现在 之前 任何 @eel.expose。正如目前所写,您可能会在 JavaScript 控制台中看到有关无法加载某些资源的错误。