You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WASM构建可选参数使用:Go WASM调用IndexedDB传keyPath参数报错如何解决

问题解决方法

你之前的几种传参写法都没有正确构造JS对象格式的参数,所以IndexedDB无法识别配置项:

  • 直接传字符串字面量,JS侧接收到的是普通字符串而非配置对象
  • 传JSON序列化后的字节数组,对应到JS侧是Uint8Array类型,也不符合参数要求
  • 把多个参数拼接为单个字符串属于语法错误,完全无法被解析

正确实现步骤

  1. 构造符合要求的createObjectStore配置参数,两种写法均可:
// 写法1:直接传入Go map,syscall/js会自动转换为JS对象
storeOptions := map[string]string{"keyPath": "id"}
objectStore := result.Call("createObjectStore", "employee", storeOptions)

// 写法2:显式创建JS对象赋值,兼容性更强
// storeOptions := js.Global().Get("Object").New()
// storeOptions.Set("keyPath", "id")
// objectStore := result.Call("createObjectStore", "employee", storeOptions)
  1. 修正add方法的参数,不能直接传Go字符串,要构造对应JS对象:
// 写法1:用map构造
empData := map[string]interface{}{
    "id": "00-01",
    "name": "Karam",
    "age": 19,
    "email": "kenny@planet.org",
}
objectStore.Call("add", empData)

// 写法2:显式创建JS对象
// empData := js.Global().Get("Object").New()
// empData.Set("id", "00-01")
// empData.Set("name", "Karam")
// empData.Set("age", 19)
// empData.Set("email", "kenny@planet.org")
// objectStore.Call("add", empData)

完整修改后的代码片段

var dbUpgrade js.Func
var result, request js.Value

dbUpgrade = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
    defer dbUpgrade.Release()
    result = this.Get("result")

    // 构造存储配置对象
    storeOptions := map[string]string{"keyPath": "id"}
    objectStore := result.Call("createObjectStore", "employee", storeOptions)

    // 构造要插入的数据对象
    empData := map[string]interface{}{
        "id": "00-01",
        "name": "Karam",
        "age": 19,
        "email": "kenny@planet.org",
    }
    objectStore.Call("add", empData)

    window.Call("alert", "First record posted.")
    return nil
})
request.Set("onupgradeneeded", dbUpgrade)

内容的提问来源于stack exchange,提问作者Hasan A Yousef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:06:01