【问题标题】:How to assign the output of a Fetch call to a variable (JavaScript)如何将 Fetch 调用的输出分配给变量 (JavaScript)
【发布时间】:2021-12-23 08:31:49
【问题描述】:

我尝试将 Fetch 调用的输出连接到我的页面变量,但我似乎无法做到。 你能看看下面的代码并帮助我吗?

enter image description here

【问题讨论】:

  • 请勿发布代码、数据、错误消息等的图片 - 将文本复制或输入到问题中。请保留将图像用于图表或演示渲染错误,这些无法通过文本准确描述的事情。有关更多信息,请参阅元常见问题解答条目Why not upload images of code/errors when asking a question? 请edit 您的问题包含文本。

标签: javascript fetch variable-assignment


【解决方案1】:

我认为 async/await 方法可以解决您的问题。

async outputvariable() {
  try {

     const response = await fetch('https://api2.online-conve', {
         method: 'GET',
         credentials: 'same-origin'
     });
      const rlt = await response.json();
      return rlt;
  } catch (error) {
   console.error(error);
  }
}

【讨论】:

    【解决方案2】:

    您必须将周围的函数设为异步函数,然后等待响应。

    async function(){
        try{
            var outputVariable = await fetch("URL").text();
            // Use outputVariable
        } catch(e){
            console.log('error', e);
        }
    }
    

    【讨论】:

    • 我试过这个。不幸的是不会工作。 Javascript 给出错误:“SyntaxError: Invalid or unexpected token” for use of "\\" 之后,我猜整个事情都没有意义了
    • 抱歉,使用了不正确的斜线。应该是正斜杠而不是反斜杠。错字,不是错误的代码。它现在应该可以工作了。
    • 我使用更正后的代码,现在得到: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'outputvariable')
    • 如果你去掉.text()并用你的url替换url,outputVariable的值是多少?
    • 同样的错误。似乎它对异步部分没有任何作用......未捕获(承诺)TypeError:无法读取未定义的属性(读取'输出变量')
    【解决方案3】:

    或者你可以使用 axios 而不是 fetch。

    import axios from 'axios';
    
    const response = await axios('https://api2.online');
    
    console.log(response.data);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 2012-12-12
      相关资源
      最近更新 更多