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

162
Visualizações
Javascript: variable not null becomes undefined after fetch function + headers problem

Hi I'm in trouble using fetch function, in this moment I wanna change the headers after a login using the token 'l' so it gives me success if is a real user. This is the code:

var l; //variable l use to put the token in the future

Login

const login = document.getElementById('login');

    const nome = document.getElementById('lnome');
    const pass = document.getElementById('lpass');

    const item = {
        Username: nome.value.trim(),
        Password: pass.value.trim()
    };

    fetch(uri_2, {
        credentials: 'include',
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(item)
    })
        .then(response => {
           //check in the response if is a user, otherwise do catch     
        })
        .then((res) => {
            nome.value = '';
            pass.value = '';

            window.alert('Login Bem Sucedido :');


            //HERE I HAVE PROBLEM PUT THE TOKEN, THIS CODE IS WRONG               

            //setRequestHeader("Authorization", 'Bearer ' + l);
            headers: new Headers({
                'Authorization': 'Basic ' + btoa('username:password'),
                'Content-Type': 'application/x-www-form-urlencoded'
            }), 

            //HERE I PUT THE TOKEN IN A VAR L

            l = res;
            window.location.href = url_1;

        })
       
        .catch(error => {
            //here i have a bunch of alerts to check if is a valid user
        });
}

Page List after login


$(function () {
    var $users_A = $('#users_A');
    debugger;
        $.ajax({
            url: uri_3_2,
            type: 'GET',
            dataType: 'json',

            //HERE IS WHEN I NEED TO PUT THE TOKEN
            beforeSend: function (request) {
                request.setRequestHeader("Authorization",'Bearer '+l);
            },

            success: function (data) {
                console.log('Sucess YAYYYYYYYY');
            },
            error: function (xhr, textStatus, errorThrown) {
                console.log('Error in Operation');
                
            }
        });
    });

I did debugger in both functions and for my surprise, before the method ajax is call, I can put the token into the variable l BUT after the method ajax, it is undefined the token and I don´t understand why, its because of using fetch and in the other hand using ajax, its because of the headers of the fetch or its other error?

Any answer is welcome.

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