This first issue is that you are storing the shortened links in an array in the program and not in a database. As long as the one program is running and it’s the only program that’s running, that’s fine, but this will fail anytime the program is restarted. It may pass the tests this way, but you really need to tie into a DB, especially since you’ve already started some of the work to tie in MongoDB.
Second, you’re not logging enough. You had one place where you logged successfully validated URLs. I ran a fork of your project, and nothing was logged, which means there were no validated URLs. When I added some logging to your project like:
app.post('/api/shorturl/', (req, res) => {
console.log(req.body.url);
const {url } = req.body;
const noHTTPSurl = url.replace(/^https?:\/\//, '');
console.log(noHTTPSurl);
// check if url is valid
dns.lookup(noHTTPSurl, (err) => {
if(err) {
console.log("everything is invalid");
return res.json ({
error: 'Invalid URL'
});
it logged
https://boilerplate-project-urlshortener-6.jeremyagray.repl.co/?v=1630244864833
boilerplate-project-urlshortener-6.jeremyagray.repl.co/?v=1630244864833
everything is invalid
https://boilerplate-project-urlshortener-6.jeremyagray.repl.co/?v=1630244865032
boilerplate-project-urlshortener-6.jeremyagray.repl.co/?v=1630244865032
everything is invalid
ftp:/john-doe.org
ftp:/john-doe.org
everything is invalid
So your validation is not working. It removes (some of) the protocols and the separator, but does nothing with the URL parameters, and hence does not return a hostname required by dns.lookup()
. To give you an idea of how I would log the other route to debug, here is my version of your code:
app.get('/api/shorturl/:id', (req, res) => {
console.log(req.body);
console.log(req.params);
console.log(req.query);
console.log(req.params.id);
const {id} = req.params;
const link = links.find( l=>l.short_url === id);
if(link) {
console.log(link.original_url);
return res.redirect(link.original_url);
} else {
console.log({
error: 'No short url'
});
return res.json ({
error: 'No short url'
});
}
});
which produces
{}
{ id: 'undefined' }
{}
undefined
{ error: 'No short url' }
This is actually expected since the other route is not actually returning an ID so there is no ID for the fCC tests to send.