Help with dns.lookup(host, cb)

I am trying to complete the url shortner project on glitch and we were instructed to check if the url is correct format or the host is valid with dns.lookup(). But i am getting error that shows on browser and on console when the url is not valid instead of just getting the json file i sent in the ternary operator i made in my callback.

Here is my code for it

app.post("/api/shorturl/new", function(req, res) {
  let urlObject = new URL(req.body.url);
 
  dns.lookup(urlObject.hostname, (err, address, family) =>
    err == null ? res.json({ staus: "valid" }) : res.json({ staus: "invalid" })
  );
});

And here is the error on browser

TypeError [ERR_INVALID_URL]: Invalid URL: wiodjw
at onParseError (internal/url.js:241:17)
at new URL (internal/url.js:319:5)
at /app/server.js:42:19
at Layer.handle [as handle_request] (/rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/router/layer.js:95:5)
at next (/rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/router/layer.js:95:5)
at /rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/router/index.js:335:12)
at next (/rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/express/4.17.1/node_modules/express/lib/router/index.js:275:10)
at /rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/body-parser/1.19.0/node_modules/body-parser/lib/read.js:130:5
at invokeCallback (/rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/raw-body/2.4.0/node_modules/raw-body/index.js:224:16)
at done (/rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/raw-body/2.4.0/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/rbd/pnpm-volume/203012d0-ff9e-42c7-a29d-6bd8291dbbd4/node_modules/.registry.npmjs.org/raw-body/2.4.0/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (events.js:194:15)
at endReadableNT (_stream_readable.js:1125:12)

1 Like

Incase anyone stumble on this, i only handled my error a little bit better by using regex to make sure https://www. is included in whatever url the user submits.

2 Likes