Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
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 is much appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda