【问题标题】:Fetch API not giving response data in Node.js获取 API 未在 Node.js 中提供响应数据
【发布时间】:2021-05-16 21:19:27
【问题描述】:

我一直在尝试解决这个问题,但它给了我这个:ReferenceError: json is not defined

这是我的代码:

const fetch = require('node-fetch');

function makeAFile(text){
    fetch("http://bin.shortbin.eu:8080/documents", {
        method: "post",
        body: 'hey wassup'
    })
    .then(res => res.json())
    .then(json => console.log(json))
    .catch(err => console.log(err))
    return json
}

console.log(makeAFile('nope'))

【问题讨论】:

标签: node.js fetch fetch-api node-fetch


【解决方案1】:

您需要了解异步调用的工作原理。

const fetch = require('node-fetch');

function makeAFile(text){
    fetch("http://bin.shortbin.eu:8080/documents", { // this is async call
        method: "post",                              // might give result later in time
        body: 'hey wassup'
    })
    .then(res => res.json())
    .then(json => console.log(json))
    .catch(err => console.log(err))
    return json                     // JSON is not defined and will be return just after 'Fetch' is called which is 'undefined'

console.log(makeAFile('nope'));

要使您的代码同步,您应该像这样使用 async await:

const fetch = require('node-fetch');

async function makeAFile(text){
    let res = await fetch("http://bin.shortbin.eu:8080/documents", { // await helps you to wait here to make your code sync
        method: "post",                              
        body: 'hey wassup'
    })
     const json = res.json()
     
    return json ;                                
}

try {
const response = await makeAFile('nope')); //use try catch to catch error
console.log(response);
}
catch (error) {
console.log(`Error ${error}`);
} 

【讨论】:

    【解决方案2】:

    您似乎对如何从异步调用返回数据感到困惑。你可以使用这样的回调来做到这一点:

    const fetch = require('node-fetch');
    
    function makeAFile(text){
      return fetch("http://bin.shortbin.eu:8080/documents", {
        method: "post",
        body: text
      })
      .then(res => res.json())
      .catch(err => { console.error(err) })
    }
    
    makeAFile('nope').then((result) => console.log(result));
    

    你可以阅读更多关于它here;

    编辑:使用async/await提供解决方案

    async function makeAFile (text) {
      try { 
        const res = await fetch("http://bin.shortbin.eu:8080/documents", {
          method: "post",
          body: text
        })
        return res.json();
      } catch (err) {
        console.error(err);
      }
    }
    
    // Define an anonymous async function to allow await statements inside
    (async () => {
      // this "await" here is important
      const result = await makeAFile('nope');
      console.log(result);
      // now result is store inside of "result"
    })();
    

    【讨论】:

    • 不需要创建 Promise,因为fetch 已经是一个异步函数。
    • @Anatoly 你是对的。我已经删除了新的 Promise 分配
    • 但是如果我想存储 var 怎么办
    • @BRUH 对回调内部的结果做你想做的事。您可以将结果存储在全局变量中,但请注意调用 makeAFile 后的代码将立即运行,并且不会等待回调运行,因此无法访问更新的值。
    • @BRUH 您可以使用新的async/await 语法来摆脱回调并以线性方式调用异步函数。你可以阅读它here
    【解决方案3】:

    then 回调之外,您无权访问json。只需将您的函数设为async,这样您就可以访问它,并且外部上下文代码可以等到您的函数被解析或拒绝:

    const fetch = require('node-fetch');
    
    async function makeAFile(text){
        const res = await fetch("http://bin.shortbin.eu:8080/documents", {
            method: "post",
            body: 'hey wassup'
        })
        const json = res.json()
        console.log(json)
        return json
    }
    

    然后这样称呼它:

    try {
      const result = await makeAFile('nope')
      console.log(result)
    } catch(err) {
      console.log(err)
    }
    

    const result = makeAFile('nope').then(result => {
      console.log(result)
    })
    .catch(err => {
      console.log(err)
    });
    

    【讨论】:

    • 但是 await 必须在一个函数中,所以我收到以下错误SyntaxError: await is only valid in async function
    • 您需要在函数定义前使用'async'关键字才能使其工作。
    • 您可以查看我添加到答案中的两个呼叫示例
    【解决方案4】:
    const fetch = require('node-fetch');
    
    function makeAFile(text){
        jsonOut = ''
        fetch("http://bin.shortbin.eu:8080/documents", {
            method: "post",
            body: 'hey wassup'
        })
        .then(res => res.json())
        .then(json => jsonOut = json)
        .catch(err => console.log(err))
        return jsonOut
    }
    
    console.log(makeAFile('nope'))
    

    你不能访问 promise 中的值。只需检查此代码

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      相关资源
      最近更新 更多