代码之家  ›  专栏  ›  技术社区  ›  NealWalters

NodeJS-在函数中调用Fetch会挂起控制台

  •  0
  • NealWalters  · 技术社区  · 6 年前

    我在React客户端遇到了一个问题,所以我使用了一个更简单的单文件节点程序来重现这个错误。在react客户端中,我没有得到任何数据。通过使用Postman,我能够执行“获取”并检索JSON数据。

    有人能帮我把这个挂起来吗?

    我最近在服务器端gettranslations中做了一个类似的函数,这样我就可以从一个函数调用MongoDB。( NodeJS ASync call of MongoClient GetData routine )1.我想我的回答是一样的。

    我曾考虑过使用“wait”,但我不使用异步函数。在我刚才提到的上述示例中,我不需要“wait”,因为函数使用“wait”。然后是“模式”。

    部分代码:

    const fetch = require("node-fetch");
    
    function getDBLanguagesAndConvertToDataTable(fromLanguage, toLanguage) { 
      // TODO implement from/to Language in URL below  
      console.log("Function: " + getFormattedTime())
      return fetch('http://localhost:3001/api/gettranslations/en-US/es-MX', {
                      method: 'GET',
                      headers: {
                        'Accept': 'application/json'
                      }
        })
      .then(function(data) {
         // do something with the data 
         console.log("Status:", data.status)
         console.log("data from DB:")
         console.log(JSON.stringify(data)) 
         console.log("data.body:")
         console.log(JSON.stringify(data.json())) 
         // I call another function here to reshape the data, 
         // but even with that commented out, same issue. 
         return data.json() 
      })
      .catch(function(err){
         console.log("Error:" + err)
         throw new Error(err) 
      })
    }
    
    
    console.log("------- Test with Fetch/Get/FromWebservice -------")
    console.log(getFormattedTime())
    var fromLanguage = 'en-US'
    var toLanguage = 'es-MX'
    
    getDBLanguagesAndConvertToDataTable(fromLanguage, toLanguage)
        .then(function (dataTable) {
            console.log(getFormattedTime, " Back from call fetch")
            var strDataTable = JSON.stringify(dataTable, null, 3);  
            console.log("ReactTables(): Resulting DataTable=")
            console.log(strDataTable) 
            console.log(getFormattedTime(), "The end of tests ")    
    
    })
    

    我运行“node test.js”。它显示以下内容并挂起。我得休息一下才能结束这一切。

    ------- Test with Fetch/Get/FromWebservice -------
    2020-08-26-20-43-08
    Function: 2020-08-26-20-43-08
    

    第2部分-添加捕获后

    修订守则:

    function getDBLanguagesAndConvertToDataTable(fromLanguage, toLanguage) { 
      // TODO implement from/to Language in URL below  
      console.log("Function: " + getFormattedTime())
      return fetch('http://localhost:3001/api/gettranslations/en-US/es-MX', {
                      method: 'GET',
                      headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                      }
        })
      .then(function(data) {
         // do something with the data 
         console.log("Status:", data.status)
         console.log("data from Fetch:")
         console.log(JSON.stringify(data)) 
         console.log("data.json():")
         console.log(JSON.stringify(data.json())) 
     
         //var tmpDataTable = convertMongoLanguagesToDataTable(data.json())
         //return tmpDataTable
         return data.json() 
      })
      .catch(function(err){
         console.log("Fetch Error:" + err)
         throw new Error(err) 
      })
    }
    
    /*
    console.log("------- Test with variable data-------------")
    console.log(getFormattedTime())
    dataTable = convertMongoLanguagesToDataTable(dbGetResults) 
    var strDataTable = JSON.stringify(dataTable, null, 3);  
    console.log("Resulting DataTable=")
    console.log(strDataTable) 
    console.log("\n\n")
    */ 
    
    console.log("------- Test with Fetch/Get/FromWebservice -------")
    console.log(getFormattedTime())
    var fromLanguage = 'en-US'
    var toLanguage = 'es-MX'
    
    getDBLanguagesAndConvertToDataTable(fromLanguage, toLanguage)
        .then(function (dataTable) {
            console.log(getFormattedTime, " Back from call fetch")
            var strDataTable = JSON.stringify(dataTable, null, 3);  
            console.log("ReactTables(): Resulting DataTable=")
            console.log(strDataTable) 
            console.log(getFormattedTime(), "The end of tests ")    
        .catch(function (err){
            console.log("call function getDBLanguagesAndConvertToDataTable error:", 
                         getFormattedTime(), "The end of tests ")    
            
        })
    })
    

    输出:

    ------- Test with Fetch/Get/FromWebservice -------
    2020-8-26-21-31-5
    Function: 2020-8-26-21-31-5
    Status: 200
    data from Fetch:
    {"size":0,"timeout":0}
    data.body:
    {}
    Fetch Error:TypeError: body used already for: http://localhost:3001/api/gettranslations/en-US/es-MX
    (node:38732) UnhandledPromiseRejectionWarning: Error: TypeError: body used already for: http://localhost:3001/api/gettranslations/en-US/es-MX
        at E:\GitHub\NealWalters\KyleShedCompanyPOC\shedco-backend\test_convert_languages_to_data_table.js:144:12
        at processTicksAndRejections (internal/process/task_queues.js:97:5)
    (node:38732) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
    (node:38732) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   NealWalters    6 年前

    根据上面@jfriend00的评论,我需要有。抓住每一个。然后是声明。

    一旦我得到了捕获,我就得到了一个错误,因为我试图访问流两次,所以现在我只是注释掉了额外的控制台。记录从提取返回的“data”变量。 (发现此处描述的错误: https://github.com/node-fetch/node-fetch/issues/533 )

    在这一点上,我可以在控制台的webservice中看到我的JSON,不再挂起!

    function getDBLanguagesAndConvertToDataTable(fromLanguage, toLanguage) { 
      // TODO implement from/to Language in URL below  
      console.log("Function: " + getFormattedTime())
      return fetch('http://localhost:3001/api/gettranslations/en-US/es-MX', {
                      method: 'GET',
                      headers: {
                        'Accept': 'application/json'
                      }
        })
      .then(function(data) {
         // do something with the data 
         /*
         console.log("Status:", data.status)
         console.log("data from Fetch:")
         console.log(JSON.stringify(data)) 
         console.log("data.json():")
         console.log(JSON.stringify(data.json())) 
         */ 
     
         //var tmpDataTable = convertMongoLanguagesToDataTable(data.json())
         //return tmpDataTable
         return data.json() 
      })
      .catch(function(err){
         console.log("Fetch Error:" + err)
         throw new Error(err) 
      })
    }
    
    /*
    console.log("------- Test with variable data-------------")
    console.log(getFormattedTime())
    dataTable = convertMongoLanguagesToDataTable(dbGetResults) 
    var strDataTable = JSON.stringify(dataTable, null, 3);  
    console.log("Resulting DataTable=")
    console.log(strDataTable) 
    console.log("\n\n")
    */ 
    
    console.log("------- Test with Fetch/Get/FromWebservice -------")
    console.log(getFormattedTime())
    var fromLanguage = 'en-US'
    var toLanguage = 'es-MX'
    
    getDBLanguagesAndConvertToDataTable(fromLanguage, toLanguage)
        .then(function (dataTable) {
            console.log(getFormattedTime, " Back from call fetch")
            var strDataTable = JSON.stringify(dataTable, null, 3);  
            console.log("ReactTables(): Resulting DataTable=")
            console.log(strDataTable) 
            console.log(getFormattedTime(), "The end of tests ")    
        })
        .catch(function (err){
            console.log("call function getDBLanguagesAndConvertToDataTable error:", 
                         getFormattedTime(), "The end of tests ")    
            
        })
    
    推荐文章