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

135
Visualizações
How can I connect to a API using fetch and bearer token?

I would like to connect to REST API that uses a token Bearer. I try the JS code below :

sessionStorage.setItem('MCToken',
    JSON.stringify('123456')
);

let datastructuresAPI = () => {
    let token = JSON.parse(sessionStorage.getItem('MCToken'));
    let header = new Headers({
        'Cache-Control': 'no-cache',
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    });
    let response = fetch('https://mon_url',{
        method: 'POST',
        headers: header,
        body:JSON.stringify({
            "methodName":"connect",
            'grant_type': 'client_credentials',
            "serviceName":"ConnectionService"
        }),
        'x-frame': 'same-origin',
        mode: 'no-cors'       
    });
    console.log(response)
}
datastructuresAPI();

But I can’t connect, I have these message (the first is the result of the console.log)

enter image description here

enter image description here

Thank you for your help

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

0

Fetch function is an async function and you should wait it.

fetch(...)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

For the other result (401) are you sure that your REST API waits token with Bearer {token}? It could be only {token}.

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