Hi, so I’ve completed the challenge, and I can submit a URL to get the short URL. I can submit a short URL and get redirected, but all the tests are failing, except 1. It makes no sense because when I test on Gitpod (my live link), it works (except for some URLs when redirected, where Firefox raises a security error in the Gitpod browser)
Here’s what I have in my index.js:
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const dns = require('dns');
const mongoose = require('mongoose');
const app = express();
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
// for body parser
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const DB_URL = process.env.DB_URL;
// Connect to MongoDB using Mongoose, targeting the URLS database in the FCC-Mongoose cluster
try {
mongoose.connect(DB_URL);
} catch (error) {
console.error('Error connecting to MongoDB:', error);
return;
}
// create schema to link to the "table"/collection
const urlSchema = new mongoose.Schema({
short_url: Number,
url: String
})
// create model using the schema
const urls = mongoose.model('urls', urlSchema, 'urls');
app.get('/', (req, res) => {
res.sendFile(process.cwd() + '/views/index.html');
});
// GET endpoint to redirect
app.get('/api/shorturl/:shorturl', async (req, res) => {
const shortUrlID = req.params.shorturl;
if (isNaN(shortUrlID))
{
return res.status(400).json({ error: 'invalid shorturl' });
}
// find the url based on the short_url
try {
const result = await urls.findOne({short_url: parseInt(shortUrlID)});
console.log(result);
return res.status(302).redirect(result.url);
} catch (error) {
console.error('Error fetching URL:', error);
return res.status(500).json({ error: 'internal server error' });
}
});
// POST to add URL to list
app.post('/api/shorturl', (req, res) =>{
const url = req.body.url;
// check if url is valid
const re = /^(https?:\/\/www\.)[a-zA-Z0-9\-]+\.[a-zA-Z]{2,}(\/\S*)?$/;
if (!re.test(url))
{
return res.status(400).json({ error: 'invalid url' });
}
console.log(url);
// Extract hostname for DNS lookup
let hostname;
try {
hostname = new URL(url).hostname;
} catch (error) {
return res.status(500).json({ error: 'cant extract hostname' });
}
// check the hostname of the url
dns.lookup(hostname, async (err, address, family) => {
if (err && err.code === "ENOTFOUND") {
return res.status(404).json({ error: 'invalid url' });
}
try {
const result = await urls.findOne({url: url});
if (!result)
{
// Find the highest short_url and increment, starting from 2
const last = await urls.findOne().sort({ short_url: -1 });
const nextShortUrl = last && last.short_url ? last.short_url + 1 : 2;
// create and save new "row"/document
const newUrl = new urls({
short_url: nextShortUrl,
url: url
});
await newUrl.save();
return res.status(200).json({ original_url: newUrl.url, short_url: newUrl.short_url });
}
return res.status(400).json({error: "url already in database"})
} catch (error) {
console.error('Error fetching URL:', error);
return res.status(500).json({ error: 'internal server error' });
}
});
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
The error I get sometimes on redirect in the GitPod browser:
What am I getting wrong here? Thanks in advance for the help!
