【问题标题】:Accessing promise data from Node API inside React fetch call在 React fetch 调用中从 Node API 访问 promise 数据
【发布时间】:2019-07-13 10:58:51
【问题描述】:

我正在组合一个 React 应用程序,该应用程序使用来自我本地计算机上的 Node/Express REST API 的数据。我有一个简单的res.json 返回一个 Sequelize 对象,我正在通过我创建的服务访问它。显然,我最终会将对象放入 state,但我目前无法访问这些值。

const options = {
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: JSON.stringify({email: "matthewharp@gmail.com", password: "M1nerals"})
};
fetch('http://localhost:3000/users/sign_in', options)
    .then(response => console.log(response.json()));

我在控制台中得到结果,但它们卡在 [[PromiseValue]] 中。

我一定错过了某种异步步骤,但我不确定是什么。

【问题讨论】:

  • fetch('http://localhost:3000/users/sign_in', options).then(response => response.json()).then(data => console.log(data));

标签: javascript ajax reactjs express


【解决方案1】:

json 方法返回一个承诺,您需要等待。这样做:

fetch('http://localhost:3000/users/sign_in', options)
    .then(response => response.json())
    .then(obj => console.log(obj));

【讨论】:

    【解决方案2】:

    您遇到此错误是因为 response.json() 返回了一个承诺。

    你需要做 fetch('http://localhost:3000/users/sign_in', options) .then(response => response.json()) .then(res => console.log(res));

    【讨论】:

      【解决方案3】:

      您需要从 fetch 调用中返回承诺,否则您需要在 then 中对 json 承诺采取行动。

      const options = {
          method: "POST",
          headers: {
              "Content-Type": "application/x-www-form-urlencoded"
          },
          body: JSON.stringify({email: "matthewharp@gmail.com", password: "M1nerals"})
      };
      return fetch('http://localhost:3000/users/sign_in', options)
          .then(response => {
               console.log(response.json())
               return response.json()
          }
      );
      

      或者...

      const options = {
              method: "POST",
              headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
              },
              body: JSON.stringify({email: "matthewharp@gmail.com", password: "M1nerals"})
          };
         fetch('http://localhost:3000/users/sign_in', options)
              .then(response => {
                   console.log(response.json())
                  response.json().then( result => {
                     // whatever you're doing with the data here.
              }
          );
      

      【讨论】:

        【解决方案4】:

        看看fetch api: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

        您需要一个单独的 then 链接来获取准备好的 json 数据,它会为您提供值。

        ('http://localhost:3000/users/sign_in', options)
        .then(function(response) {
            return response.json();
        })
        .then(function(myJson) {
            console.log(JSON.stringify(myJson));
        });
        

        【讨论】:

          猜你喜欢
          • 2020-10-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-10
          • 2020-09-03
          • 2019-04-26
          相关资源
          最近更新 更多