Url shortner service- cant figure out where I'm wrong

my url shortner service is working absolutely fine but I’m unable to pass the test.
Please help me find where I’m wrong.

Here’s my code

const mySecret = process.env['MONGO_URI']
const PORT = process.env['PORT']
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bodyParser = require('body-parser')
const dns = require('dns')
const urlParser = require('url')
const app = express();



// Basic Configuration
const port = process.env['PORT'] || 3000;
mongoose.connect(mySecret, { useNewUrlParser: true, useUnifiedTopology: true });


const urlSchema = new mongoose.Schema({url: String})
const Url = mongoose.model('Url', urlSchema)

app.use(cors());

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/new',bodyParser.urlencoded({extended:false}),function(req, res) {
  const bodyurl = req.body.url
  const lookup = dns.lookup(urlParser.parse(bodyurl).hostname,(err,address)=>{
    if(err) return console.log(err)
    if(!address){
      return res.json({ error: 'invalid url' })
    }else{
      const url = new Url({url:bodyurl})
      url.save((err,data)=>{
        res.json({
          original_url: data.url,
          short_url: data.id
        })
      })
    }
    console.log('dns',err)
    console.log('address',address)
  })
});

app.get("*", (err,res)=>{
  res.json({error:"Invalid URL"})
})

app.get('/api/shorturl/:id',(req,res)=>{
  const id = req.params.id
  Url.findById(id,(err,data)=>{
    if(!data){
      res.json({error:"Invalid URL"})
    }else{
      res.redirect(data.url)
    }
  })
})

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

Your project link(s)

solution: https://replit.com/@sandeepgumaste/boilerplate-project-urlshortener

Your browser information:

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

Challenge: URL Shortener Microservice

Link to the challenge:

There are several problems with this route:

And this route catches everything, so your redirect route is never seen.

Log all the route inputs and responses for all your routes and you’ll be able to debug much more easily.

1 Like