I’ve been trying for days to try to figure out how to use dns.lookup since it is suggested to use it in the challenge. I’m sure I put in the correct arguments, but I’m not for sure how to use it to check if the url is vaild.
I replace https:// and http:// before putting it as the first argument to dns.lookup(hostname, options, callback);
The reason I took off https… and http… was because it was triggering an error.
The hostname parameter seems to expect either www.websitename.com or websitename.com…
but when I manually input other values into the hotname parameter such as “23423423” or etc, dns.lookup returns an object with a property called hostname with the value “23423423” …
…is it suppose to do that? or am I doing something wrong?
Since the 4th test in the challenge is " If you pass an invalid URL that doesn’t follow the valid http://www.example.com
format, the JSON response will contain { error: 'invalid url' }
",
And since I couldn’t get dns.lookup to work, I decided to search the user inputted string for http and https, and if it didn’t include it, the code would yield {error: “invalid url”} and return, exit the function.
If you would like to look at my code, it’s below, but since I was testing and trying to figure out things I have a lot of commented out code (I’m Sorry if it makes it harder for you to look through it in anyway. Initially I try to figure things out, test things, from memory or experiment to see if I can get it to work before trying to look online or elsewhere for information).
mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true}); // FCC added the second property: value pair
db = mongoose.connection;
db.on("error", console.error.bind(console, "There Has Been A Connection Error!"));
db.on("open", function() {
console.log(db.readyState === 1, "The Database Is Connected. TYG.")
// The rest of the code:
const urlSchema = new mongoose.Schema({
url: String,
ID: Number
});
const Url = mongoose.model("Url", urlSchema);
app.route("/api/shorturl/new")
.post(async function shortUrl(req, res) {
if (!req.body.url.includes("http")) {
res.json({error: "invalid url"});
return;
}
const urlParameter = await req.body.url;
const hostname = await req.body.url.replace(/https?:\/\//, "");
// res.json({newURL: new URL(req.body.url)}) returns "https://www.noelbray.com/"
let validUrl = await dns.lookup(hostname, {hints: dns.ADDRCONFIG}, function(err, address, family) {
if (err) console.log(err)
// if (err) return err;
console.log("address: ", address, address === null)
// return address;
// if(address) {
// res.json({test: address});
// }
// resolve(address);
// return res.json({dnstest: address === null})
// if (address === null || address === undefined) res.json({error: "invalid"});
// validUrl = address;
// return res.json({address: address || "I'm trying to figure this out."});
// res.send("ok");
});
// if (validUrl) {
// // return res.json(validUrl.hostname);
// // return res.json({error: "invalid url"})
// return res.json({test: validUrl});
// } else {
// return res.json({error: "invalid url"})
// // return res.json(validUrl.code)
// }
// if(/https:\/\/wwww|http:\/\/www/.test(validUrl.hostname)) {
// return res.json(validUrl.family);
// } else {return {error: "invalid url"}};
// res.json(url);
const urlExist = await Url.exists({url: urlParameter});
// res.json("I'm working. " + urlParameter + " " + urlExist);
// TTG, I figured out the line above was causing this error: "UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"
// Explaination Which basically is telling you that you cannot send more than one res.json to a specific route, path
// article: https://stackoverflow.com/questions/52122272/err-http-headers-sent-cannot-set-headers-after-they-are-sent-to-the-client
if(urlExist) {
const doc = await Url.findOne({url: urlParameter});
res.json({
original_url: doc.url,
short_url: doc.ID
})
} else {
const shortUrlNumber = Math.floor(Math.random() * 10001);
const idExist = await Url.exists({ID: shortUrlNumber});
if (idExist) shortUrlNumber = Math.floor(Math.random() * 10001);
const url = new Url({
url: urlParameter,
ID: shortUrlNumber
});
url.save(function (err, url) {
if(err) return console.log(err);
});
// const doc = Url.findOne({url: url});
res.json({
original_url: urlParameter,
short_url: shortUrlNumber
});
}
// console.log(dns.lookup(req.body.url, (err, hostname) => {
// // if(err) return console.log(err);
// console.log("hostname is: ", hostname);
// }).hostname);
// left of with trying to figure out how to create an entry in the database.
}); // End of post method, request
app.get("/api/shorturl/:ID", async function (req, res) {
const short_url = +req.params.ID;
// I was getting an error Url not defined because I had placed this get request out of the db.on("open", function .... ) event handler function
// res.json(short_url) // the endpoint route, path is working
const short_urlExist = await Url.exists({ID: short_url});
if (short_urlExist) {
const { url } = await Url.findOne({ID: short_url});
// res.json(url); // test to see if it was working
res.redirect(url);
}
else {
res.json(`The short url ${short_url} does not exists, please try again.`)
}
}); // End of get method request
})// End of mongoose.connect db.on("open", function ... )event handler function