Why are string arguments blank when calling an async Rust function compiled to Wasm from JavaScript?

Ben*_*inC 5 rust wasm-bindgen wasm-pack

I'm using wasm_bindgen built with wasm-pack. I have a Rust function I expose to JS:

#[wasm_bindgen]
pub async fn validate_registration_token(backend_api_domain: String, token: String) -> Result<JsValue, JsValue> {

    console::log_1(&"backend_api_domain=".clone().into());
    console::log_1(&backend_api_domain.clone().into());
    console::log_1(&"token=".clone().into());
    console::log_1(&backend_api_domain.clone().into());

    let api_endpoint_get_guest_info = format!(
        "{backend_api_domain}/weddings/{token}/guests/registration/{registration_token}",
        backend_api_domain = backend_api_domain.clone(),
        token = token.clone(),
        registration_token = registration_token.clone()
    );

    console::log_1(&api_endpoint_get_guest_info.clone().into());

    let res = reqwest::Client::new()
        .get(&api_endpoint_get_guest_info)
        .send()
        .await
        .unwrap();

    let text = res.text().await.unwrap();

    let promise = js_sys::Promise::resolve(&true.into());
    let result = wasm_bindgen_futures::JsFuture::from(promise).await.unwrap();
    Ok(result)
}
Run Code Online (Sandbox Code Playgroud)

In HTML / JavaScript, I call the Rust function:

<button
    type="button"
    class="btn submit"
    onclick="wam.validate_registration_token('http://localhost:80', 'mytoken')">
    Send
</button>
Run Code Online (Sandbox Code Playgroud)

When launching the app, clicking on the Send button will call my Rust function, but both String params seem to be blank / missing.

Here's the console trace from function above:

backend_api_domain=

token=

/weddings//guests/registration/AAAA
Run Code Online (Sandbox Code Playgroud)

I am not sure what I am doing wrong here. Should I change the way I call the Rust function from JavaScript?

Here's the full code example to reproduce

Ben*_*inC 4

终于成功解决了这个问题!感谢用户 Pauan 在 Rust Discord 中的帮助。我的错误是没有在 JS 中正确初始化 WASM。

wait init('./front_bg.wasm') 的返回值是原始 WebAssembly 导出(您通常不应该使用),而 ./front.js 模块包装这些导出,以便它们能够正常工作,因此您必须使用./front.js中定义的函数,而不是init返回的函数

请参阅https://discordapp.com/channels/442252698964721669/443151097398296587/693385649750933564

将 HTML 中的脚本标记更改为以下标记:

import init, * as wam from './front.js';
const run = async () => {
    await init('./front_bg.wasm');
    window.wam = wam;
};
run();
Run Code Online (Sandbox Code Playgroud)

谢谢 !