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

95
Visualizações
What can I do so object.property doesn't return undefined?

I'm trying to create a function that first fetches the JWT access tokens from my current session and then applies that to the Authorization header of my actual request. This works fine, but the end result is that I want to return the full response object.

I've tried assigning some of the output to a output object, but when I try to console.log some of the properties, then it just returns undefined. If I do console.log inside the browser, then I can see the output but I can never print the actual properties.

export default function fetcher(url, method, body = null) {
  const output = {}
  fetch("/api/auth/session")
    .then((response) => {
      return response.json()
    })
    .then((data) => {
      const token = data.user.accessToken
      if (method.toLowerCase() == "post") {
        const res = fetch(url, {
          method: "post",
          headers: {
            Authorization: "Bearer " + token,
            Accept: "application/json, text/plain, */*",
            "Content-Type": "application/json",
          },
          body: body,
        }).then((response) => {
          Object.assign(output, {
            status: response.status,
          })
        })
      } else {
        const res = fetch(url, {
          method: "get",
          headers: {
            Authorization: "Bearer " + token,
            Accept: "application/json, text/plain, */*",
            "Content-Type": "application/json",
          },
        })
          .then((response) => response.json())

          .then((data) => {
            Object.assign(output, data)
          })
      }
    })
    .catch((err) => {
      // Do something for an error here
    })
  console.log(output)
  console.log(output.status)

  return output
}

Console.logs

End goal is to call the function from some other file like this

const test = fetcher("http://api.localhost/v1/projects", "post", JSON.stringify({ name: event.target.name.value }))

console.log(test.status)
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