0

自从我开始阅读 IndexedDB 以来已经有几个小时了,我遇到了一些问题。这是我从https://medium.com/@AndyHaskell2013/build-a-basic-web-app-with-indexeddb-8ab4f83f8bdahttps://gist.github.com/JamesMessinger/a0d6389a5d0e3a24814b遵循的代码,它只是放为了理解起见,在一起很糟糕。所以我想要做的是将密钥存储到 IndexedDB 中,以便我可以使用它来使用 ECIES 方案加密事物。

相关代码(先后顺序):

var secretKey = eccrypto.generatePrivate();

window.genSKey = function()
{
 openDB();
 console.log(secretKey);
 return;
}
window.openDB = function()
{
let db;
let dbReq = indexedDB.open('ln', 1);
dbReq.onupgradeneeded = function(event) {
  // Set the db variable to our database so we can use it!  
  db = event.target.result;

  // Create an object store named notes. Object stores
  // in databases are where data are stored.
  let skey = db.createObjectStore('skey', {keyPath: "id"});
}
dbReq.onsuccess = function(event) {
  db = event.target.result;

  setSkey(db);
  getSkey(db);

}
dbReq.onerror = function(event) {
  alert('error opening database ' + event.target.errorCode);
}
}

window.setSkey = function(db) {
    // Start a database transaction and get the notes object store
    let tx = db.transaction(['skey'], 'readwrite');
    let store = tx.objectStore('skey');
    // Put the sticky note into the object store
    store.put({id: 1, secretKey});
    // Wait for the database transaction to complete
    tx.oncomplete = function() { console.log('private key was saved') }
    tx.onerror = function(event) {
      alert('error storing private key ' + event.target.errorCode);
    }
  }

  window.getSkey = function(db)
  {
      // Set up an object store and transaction
let tx = db.transaction(['skey'], 'readonly');
let store = tx.objectStore('skey');
// Set up a request to get the sticky note with the key 1
let req = store.get(1);
// We can use the note if the request succeeds, getting it in the
// onsuccess handler
req.onsuccess = function(event) {
  let skey = event.target.result;
  if (skey) {
    console.log(skey);
  } else {
    console.log("skey 1 not found")
  }
}
// If we get an error, like that the note wasn't in the object
// store, we handle the error in the onerror handler
req.onerror = function(event) {
  alert('error getting note 1 ' + event.target.errorCode);
}

由于某种原因,在前端脚本中调用 genSKey 时,我收到以下控制台错误:

Uncaught DOMException: Failed to execute 'transaction' on 'IDBDatabase': One of the specified object stores was not found.
    at window.setSkey (http://127.0.0.1:5500/browserify/builds/genKey.js:26763:17)
    at IDBOpenDBRequest.dbReq.onsuccess (http://127.0.0.1:5500/browserify/builds/genKey.js:26752:3)
window.setSkey @ genKey.js:26763
dbReq.onsuccess @ genKey.js:26752
IndexedDB (async)
window.openDB @ genKey.js:26740
window.genSKey @ genKey.js:26601
signupData @ signup.html:186
onclick @ signup.html:64

控制台记录了更多内容,但其他内容与手头的问题无关。我不确定自己做错了什么,而且我整天都在做这件事。一些洞察力对我来说意味着世界,谢谢。

4

1 回答 1

1

您可能创建了没有对象存储的数据库。要触发onupgradeneeded它将创建对象存储,您必须连接到具有更高版本号的数据库。

于 2021-01-06T20:19:16.937 回答