Unable to pass 2 Tests in URL Shortener Microservice

Tell us what’s happening:

Unable to Complete the task for URL Shortener Microservice

I have tried everything and I do not know what is the problem. i only passed first and last test

Your code so far

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const { MongoClient } = require('mongodb');
const dns = require('dns');
const urlparser = require('url')


const mongoUri = process.env.MONGO_URI || 'mongodb+srv://burhan:<rock60090>@cluster0.ane2gy8.mongodb.net/urlshortener?retryWrites=true&w=majority&appName=Cluster0';
const client = new MongoClient(mongoUri);
const db = client.db("urlshortner")
const urls = db.collection("urlforshortner")
console.log("MONGO_URI:", mongoUri); // Add this line for debugging

// Basic Configuration
const port = process.env.PORT || 3000;

app.use(cors());
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.use('/public', express.static(`${process.cwd()}/public`));

app.get('/', function (req, res) {
  res.sendFile(process.cwd() + '/views/index.html');
});

// Your first API endpoint
app.post('/api/shorturl', async (req, res) => {
  console.log(req.body);
  const url = req.body.url;
  console.log(url);

  try {
    // Validate the URL
    const hostname = new urlparser(url).hostname;

    // Perform DNS lookup
    dns.lookup(hostname, (err, address) => {
      if (err || !address) {
        res.json({ error: "Invalid URL" });
      } else {
        // Proceed with database operations if URL is valid
        urls.countDocuments({}, async (err, urlcount) => {
          if (err) {
            res.status(500).json({ error: "Database error" });
            return;
          }

          const urlDoc = {
            url,
            short_url: urlcount
          };

          try {
            const result = await urls.insertOne(urlDoc);
            console.log(result);
            res.json({ original_url: url, short_url: urlcount });
          } catch (err) {
            res.status(500).json({ error: "Database insertion error" });
          }
        });
      }
    });
  } catch (e) {
    // Handle URL constructor errors (invalid URL format)
    res.json({ error: "Invalid URL" });
  }
});

app.get("/api/shorturl/:short_url", async (req, res) => {
  const shorturl = req.params.short_url
  const urlDoc = await urls.findOne({
    short_url: +shorturl
  })
  res.redirect(urlDoc.url)
})

app.listen(port, function () {
  console.log(`Listening on port ${port}`);
});

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36

Challenge Information:

Back End Development and APIs Projects - URL Shortener Microservice

Please Tell us what’s happening in your own words.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!


I am not able to pass the 2nd and 3rd test