I am trying to do the URL Shortener Microservice project.
I entered https://www.freecodecamp.org into the Input and pressed the Post URL button
I cannot work out why I get the following appearing in my console:
npm start
> shorturl@0.0.3 start
> node index.js
Listening on port 3000
https://www.freecodecamp.org
VALID
node:events:505
throw er; // Unhandled 'error' event
^
Here is the code that I am running:
app.post('/api/shorturl', function(req, res) {
const passedUrl = req.body.url;
console.log(passedUrl);
//based on isValidHttpUrl is from Pavlo (stackoverflow) Apr 18, 2017 at 8:22
function isValidUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return (url.protocol === "http:" || url.protocol === "https:") && url.hostname.substr(0, 4) === "www." && url.hostname.substr(0, 4) === "www." && url.protocol + '//' + url.hostname === string;
}
if (isValidUrl(passedUrl)) {
console.log("VALID");
//Check if URL already in database
urlShort.findOne({ URL: passedUrl }, function (err, urlShort) {
if (err) throw err;
console.log(`Store url in database:${urlShort.URL}:`);
});
}
else {
res.json({ error: 'invalid url' });
}
});
Regards
Alan