简体   繁体   中英

Cannot print object through res.json in express JS

I am trying to build an API through which I can get whois detail in the JSON output like below

在此处输入图像描述

For this, I installed the whois package from npm ( https://www.npmjs.com/package/whois[whois Link] 2 ). I tried to convert the string to object and print it in JSON format but I am not getting any output on the web but it console i can get the data easily. Can you guys please fix my error.

function whoisFunction() {
    var whois = require('whois')
    whois.lookup(url,async function(err, data) {
      try {
        a = await data.split('\n')

      }
      catch (e) {
        console.log(e)
        return e
      }

      c=[]
      for(i = 0; i < a.length; i++){
        c.push(a[i])
      }
      await console.log(typeof (c))
      console.log(c)
      return a
    })
  }
// res.json({'Headers':+whoisFunction()})
  res.status(200).json(whoisFunction())

There are async and awaits sprinkled seemingly randomly all over your function. You should realize that the only thing that is asynchronous here is whois.lookup() . console.log is not asynchronous. Array.prototype.split is not asynchronous. The callback (err, data) => {...} is not asynchronous.

If you want to use the callback pattern, then you need to use res.send() inside of the callback

(err, data) => {
  res.send(data)
}

But we got fed up with callback-patterns because of how messy it is to nest them. So instead we went over to using promises. If you have callbacks but want use promises, then you wrap the callback in a promise. You do it once, and you do it as tight to the offending callback as you can:

  function promisifiedLookup(url){
    return new Promise( (resolve, reject) => {
      whois.lookup(url, function(err, data) {
        if(err) reject(err)
        else resolve(data)
      })
    })
  }

So, to use async/await we need that:

  1. the calling function is declared async
  2. the called function is returning a promise (or else there is nothing to wait for)
async function whoisFunction() {
  let data = await promisifiedLookup(url)  // _NOW_ we can use await
  data = data.split('\n')
  // ...
  return data; // Because this funtion is declared async, it will automatically return promise.
}

If your express-handler is defined as async, then you now can use await here as well:

res.status(200).json(await whoisFunction())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM