简体   繁体   中英

Web3 getAccounts doesn't update when I switch Metamask addresses in browser

I have a node app that connects to a basic frontend, and one of the get calls in the server is to get the address of the user. It works the first time, however, when I manually switch addresses/accounts in Metamask plugin for the website, it doesn't update, and stays on the old address.

For reference I am simply using and connecting to a ganache test network opened on my laptop.

Relevant code below, first the 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; }
});

Then the main.html page calls client.js which has the following relevant snippet:

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();

The first time run it logs the correct address, letting me display it on the html page. But then I then remove that account from Metamask, add a different one, and restart and refresh and it shows the same old account.

Any reason why this code wouldn't update the account change in Metamask? How can I fix this? Help much appreciated.

TI think when the browser downloads anything, it caches, and fetch() is also caching the result. Change the options of fetch:

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

This should make a new request everytime you refresh the page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM