0

I was getting an issue in my React client side, so I reproduced the error using a simpler single file node program. In the react client, I'm not getting any data back. Using Postman, I'm able to do a "Get" and retrieve the JSON data.

Can someone help me to get this to run without hanging?

I recently did a similar function in the server side gettranslations so that I could call MongoDB from a function. (NodeJS ASync call of MongoClient GetData routine). I think I'm following the same pattern as my answer there.

I thought about using "await" but I'm not in an async function. And I didn't need "await' in the above example I just mentioned, since the function uses the ".then" pattern.

Partial Code:

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 ")    

})

I run "node test.js". It displays the following and hangs. I have to do CNTL-Break to end it.

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

Part 2 - after adding Catches

Revised code:

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 ")    
        
    })
})

Output:

------- 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.
NealWalters
  • 17,197
  • 42
  • 141
  • 251
  • Your call to `fetch()` is not resolving or rejecting, apparently. YOU have to figure out why that is. It's not hanging. It's just waiting for a response back from the server. You should also add a `.catch()` to your call to `getDBLanguagesAndConvertToDataTable()` so you would know if there was an error at that level. If this is your server, then debug in the server to see what it's doing with this request. – jfriend00 Aug 27 '20 at 02:12
  • FYI, there's no point to setting the `Content-Type` on a GET request as there is no content with the request (the body of the request which is what the content-type applies to is empty). – jfriend00 Aug 27 '20 at 02:29
  • @jfriend00 Thanks, please see my revised "Part 2" above. I added the catches; and it's not hanging, but new mysterious error that I've started Googling. (I can see the 3001 web service working okay; it has some console.logs in another window). – NealWalters Aug 27 '20 at 02:37
  • Ok, it's a stream and I cannot access it twice, adjusting code again. https://github.com/node-fetch/node-fetch/issues/533 – NealWalters Aug 27 '20 at 02:40
  • Got it, you were of course right about catch! I'll post my fix as answer. – NealWalters Aug 27 '20 at 02:43

1 Answers1

0

As per @jfriend00 comment above, I needed to have .catch on each .then statement.

Once I had the catch, I was getting an error because I was trying to access the stream twice, so for now I just commented out the extra console.logs on the "data" variable returned from the fetch. (Found that error described here: https://github.com/node-fetch/node-fetch/issues/533)

At that point, I could see my JSON from the webservice in the console, and no more hangs!

Revised code:

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 ")    
        
    })
NealWalters
  • 17,197
  • 42
  • 141
  • 251