【问题标题】:Post request using node-fetch not returning response使用 node-fetch 发布请求不返回响应
【发布时间】:2022-01-08 18:03:58
【问题描述】:

我是使用 node-fetch 的新手,想弄清楚为什么我没有得到任何响应数据以打印到控制台。

我正在使用一个函数来生成用于测试的 firebase 用户身份验证令牌,但我没有得到任何响应,而在邮递员中,我使用相同数据的请求正在返回我想要的内容。如您所见,我什至将数据硬编码到正文中,但它仍然没有返回任何内容。

async function firebaseSetupAuth(){
  const token1 = admin.auth().createCustomToken("xKdXw06u2tUVE72ETrJVwevCNQo1")
  const token2 = await token1
  token = token2
  const url = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=AIzaSyBoKaBKWe9x2LS_n5AHCIEM-5AB_dC99mg"
  const fetchBody = {"token": token,"returnSecureToken":true }
  console.log(JSON.stringify(fetchBody))
  const response1 = fetch(url,{
    method: "post",
    body: fetchBody,
    headers: {'Content-Type': 'application/json'}
  })
  const response2 = await response1
  console.log(response2)
}

【问题讨论】:

  • 如果您要将函数定义为async,则不应在代码中使用then。使用await 在每个返回承诺的函数之后暂停执行。
  • 我已经编辑了代码以使用 await

标签: javascript post firebase-authentication


【解决方案1】:

你需要返回fetch的结果

.then((customToken) => {
    return fetch(url,{ // return on this line
      method: "post",
      body: JSON.stringify(/*stuff*/),
      headers: {'Content-Type': 'application/json'}
    }
  )
  })

【讨论】:

  • 我已经添加了返回,但控制台仍然没有打印响应
  • 您可以尝试进一步隔离。尝试不带createCustomTokenfetch 调用,看看是否返回正确。如果是这样,createCustomTokenadmin.auth() 中可能存在问题。
  • 除了我的 fetch 之外,其他一切都正常运行
猜你喜欢
  • 1970-01-01
  • 2021-05-21
  • 2020-09-19
  • 2017-04-07
  • 1970-01-01
  • 2019-05-07
  • 2020-04-28
  • 2019-09-20
  • 2017-01-26
相关资源
最近更新 更多