【问题标题】:Translating Node JS request to an API to React Fetch syntax将 Node JS 请求转换为 API 以响应 Fetch 语法
【发布时间】:2020-07-07 07:32:39
【问题描述】:

我正在用 React-Native 编写一个向 Hubspot API 发出请求的应用程序。这给了我一些问题,因为我最初尝试使用 Node JS 请求模块发出请求,但在使用 Expo 时它不适用于 React Native。我现在尝试使用 React Native 自己的 Fetch API 向 Hubspot API 发出请求,但是在翻译我使用 Node JS 请求模块编写的初始代码时遇到了麻烦。向 Hubspot API 发出请求时出现错误。我已将两个版本的代码附加到这个问题上。谁能解释我对 Node JS 代码的翻译有什么问题?任何建议将不胜感激。 Node JS version (request succeeds)

Fetch version (request fails)

【问题讨论】:

  • 欢迎来到 StackOverflow。请以文本形式发布代码。

标签: javascript node.js react-native request hubspot


【解决方案1】:

欢迎来到 Stack Overflow :)

我认为您的fetch 请求没有正确写入。您可以直接将所有参数传递给 fetch 函数,而不是创建 new Request 常量:

fetch('https://hubapi.com/whatever/CONFIDENTIAL', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
   properties
  })
})
.catch((error) => {
  console.error(error);
});

请注意,我还在请求末尾添加了 catch 块。如果它仍然失败,您至少应该更好地了解究竟是什么失败了。

我上面引用的代码取自 React Native 文档,链接 here。文档包含很多很棒的示例,包括使用 async/await 和其他网络库。

【讨论】:

  • 这真的很有帮助,谢谢!正如我在上面的评论中所说,我认为我最初的请求失败的主要原因是我没有将正文转换为 JSON 格式。也感谢您提供示例的链接,我会在将来更多地处理请求时查看这些示例。
【解决方案2】:

我在我的 react native 项目中为你测试了它。请求成功,我当然得到This hapikey (CONFIDENTIAL) doesn't exist作为响应,因为我没有密钥,但是查询运行成功:

try {
    const response = await fetch(
        'https://api.hubapi.com/contacts/v1/contact/?hapikey=CONFIDENTIAL',
        {
            method: 'POST',
            headers: new Headers({ 'Content-Type': 'application/json' }),
            body: JSON.stringify({
                "properties": [
                    { property: 'email', value: 'test@email.com' },
                    { property: 'firstname', value: 'Sean' },
                    { property: 'lastname', value: 'Smith' },
                ]
            })
        }
    );
    const responseJson = await response.json();
    console.log("response from hubapi:", responseJson)
} catch (e) {
    console.error("Error on fetch request:", e);
}

【讨论】:

  • 这真的很有帮助,谢谢!我认为我之前的请求失败的主要原因是我没有将正文转换为 JSON 格式。
  • 我很高兴它有帮助!您能否将我的答案标记为已接受的答案,以便其他遇到相同问题的人可以直接找到解决方案?谢谢
猜你喜欢
  • 2021-07-20
  • 2021-05-22
  • 2020-01-12
  • 2018-05-22
  • 2017-12-06
  • 1970-01-01
  • 2018-01-26
  • 2020-09-23
  • 2022-01-25
相关资源
最近更新 更多