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

114
Visualizações
Extract response text from JavaScript fetch POST request

So I'm doing a POST request with some data I collect from an HTML form. However, I want to use the data the server sent back outside of the fetch call and this is causing me headaches.

The response is a JSON string that can contain the key 'userMessage'. I am able to print this data inside of the fetch call. I then return this data and store it in the variable response. I can log this whole object to the console but I cannot use it the same way as in the fetch call. This is my code:

email = document.forms["login"]["email"].value;
pwd = document.forms["login"]["pwd"].value;

data = JSON.stringify({'email':email, 'password': pwd});

response = fetch(
    "https://companyname/path", {
        method: 'POST',
        headers:
        {
            'accept': 'application/json, text/plain, */*',
            'accept-language': '[object Object]',
            'app-version': '1.0.3',
            'content-type': 'application/json'
        },
        body: data
    })
.then(res => res.json())
.then(data => {
    console.log('Success:', data['userMessage']);   //  This works
    return data;
})
.catch((error) => {
    console.error('Error:', error);
});

console.log(response);  //  This works too
alert(response['userMessage']); //  This just shows an alert saying "undefined"

Why doesn't this work? How do I go around it?

about 4 years ago · Juan Pablo Isaza
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