How to use dns.lookup within POST method? // URL shortener microservice project

Hi guys, I work on URL shortener project and am stucked. The thing I cant figure out is how to validate URL address. We are suposed to use dns.lookup(). When I use it separately it works. When I use it within POST method it always figures out that a URL is invalid, even though I post a valid one.
Here is the project on glitch: https://glitch.com/~url-shortener-lm
Here is the code:

app.post('/api/shorturl/new', (req, res, next) => {
  var originalURL = req.body.url;
  dns.lookup(originalURL, (err, address, family) => {
    if (err) {
      res.json({
        originalURL: originalURL,
        shortenedURL: "Invalid URL"
      });
    } else {
      var shortenedURL = Math.floor(Math.random()*100000).toString();
    
      var data = new Model({
        originalURL: originalURL,
        shortenedURL: shortenedURL
        });
    
      data.save(function(err, data) {
        if (err) {
          return console.error(err);
                 }
      });
    
      return res.json({
        originalURL: originalURL,
        shortenedURL: shortenedURL
      })
    };
  });
});

Can anyone please help?

Thanks a lot!

How can I replicate the problem. When I test out a valid url, I do not see an error in the server console.

If you add console.log(err) after the if (err) { line, what does it display?

Thank you for your reply. I figured it out: req.body.url gives you URL, dns.lookup needs hostname, that is why it did not work.
Here is the solution:

app.post('/api/shorturl/new', (req, res, next) => {
  const originalURL = req.body.url;
  const urlObject = new URL(originalURL);
  dns.lookup(urlObject.hostname, (err, address, family) => {
    if (err) {
      res.json({
        originalURL: originalURL,
        shortenedURL: "Invalid URL"
      });
    } else {
      let shortenedURL = Math.floor(Math.random()*100000).toString();
      
      // create an object(document) and save it on the DB
      let data = new Model({
        originalURL: originalURL,
        shortenedURL: shortenedURL
        });
    
      data.save((err, data) => {
        if (err) {
          console.error(err);
                 }
      });
    
      res.json({
        originalURL: originalURL,
        shortenedURL: shortenedURL
      })
    };
  });
});
1 Like