Web3 getAccounts在浏览器中切换小狐狸钱包地址时不更新



我有一个连接到基本前端的节点应用程序,服务器中get调用之一是获取用户的地址。它第一次工作,但是,当我在网站的小狐狸钱包插件中手动切换地址/帐户时,它不会更新,而是保留在旧地址上。

作为参考,我只是使用并连接到在笔记本电脑上打开的甘纳许测试网络。

下面的相关代码,首先是server.js

const express = require('express')
const app = express()
const port = 3000
const Web3 = require('web3');
const WEB3_PROVIDER = "HTTP://127.0.0.1:7545"
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
console.log("web3 already initialized.");
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider(WEB3_PROVIDER));
console.log("New web3 object initialized.");
}
app.get('/', (req, res) => {
res.sendFile('./main.html', { root: __dirname });
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
app.get('/get-account', async (_req, res) => {
try {
web3.eth.getAccounts().then(function(accs){ 
this_acc = accs[0];
console.log("account :: "); console.log(this_acc); 
return res.send(this_acc);
})

} catch (e) { throw e; }
});

然后,main.html页面调用具有以下相关代码段的client.js

async function updateUserAddr() {
console.log("updateUserAddr");
const response = await fetch('/get-account');
var addr_str = await response.text();
console.log(addr_str);
$('#address_id_poster').text(addr_str);
}
updateUserAddr();

第一次运行时,它会记录正确的地址,让我在 Html 页面上显示它。但随后我从小狐狸钱包中删除该帐户,添加一个不同的帐户,然后重新启动并刷新,它会显示相同的旧帐户。

此代码不会更新小狐狸钱包中的帐户更改的任何原因?我该如何解决这个问题?

TI 认为当浏览器下载任何内容时,它会缓存,并且 fetch() 也会缓存结果。更改抓取选项:

const response = await fetch(url, {
method: 'GET',
// this should invalidate caching
cache: 'no-cache',     

});

这应该在您每次刷新页面时发出新请求

最新更新