Back End Development and APIs Projects - URL Shortener Microservice

In replit, I constantly get an error message saying I got NaN for short_url which doesn’t allow me to pass the test.

I checked my code very carefully again and again, there’s no chance for short_url to get NaN. I test my code with differnt urls, both ones exsiting in datebase and ones not, I got the expected reponse to the post request and expected result in database. I never got NaN for short_url when I test it manually. So What should I do to get this test past?

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const dns = require('dns');

mongoose.connect(process.env.MONGO_URL, {
  useUnifiedTopology: true,
  useNewUrlParser: true
});

const urlSchema = new mongoose.Schema({
  original_url: {type: String, required: true },
  short_url: {type: Number}
});

const Url = mongoose.model("Url", urlSchema);
const port = process.env.PORT || 3000;

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
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', (req, res) => {
  let fixedUrl="";
  if(/^https/.test(req.body.url)){
    fixedUrl=req.body.url.slice(8);
  } else {
    fixedUrl=req.body.url.slice(7);
  }
  if(fixedUrl[fixedUrl.length-1]==="/"){
    fixedUrl=fixedUrl.substring(0, fixedUrl.length-1);
  }
   dns.lookup(fixedUrl, async(err, address) => {
    if (err) {
      res.json({ error: "invalid url" });
    } else {
      const foundDoc =await Url.findOne({ original_url: req.body.url });
      if (!foundDoc) {
        let lastDoc =await Url.find().sort({ short_url: -1 }).limit(1);
        let newUrl={};
        if (lastDoc.length===0) {
          newUrl={original_url:req.body.url, short_url:1};
        } else {
          let lastShort=lastDoc[0].short_url;
          console.log(lastShort);
          newUrl={original_url:req.body.url, short_url:lastShort*1+1};
        }
        console.log(newUrl);
        const result=await Url.create(newUrl);
        res.json({original_url:result.original_url, short_url:result.short_url});  
      } else {
        res.json({original_url:foundDoc.original_url, short_url:foundDoc.short_url});
      }
    }
  })
});

app.get('/api/shorturl/:index',async(req,res)=>{
  const index=req.params.index*1;
  const foundDoc=await Url.findOne({short_url:index});
  if(!foundDoc){
    res.json({error:'invalid url'});
  } else {
    res.redirect(foundDoc.original_url);
  }
})

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


Your project link(s)

solution: boilerplate-project-urlshortener-2 - Replit

Your browser information:

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

Challenge: Back End Development and APIs Projects - URL Shortener Microservice

Link to the challenge:

You need to add some console.log statements to figure out why your app treats:
https://weather.com/weather/today/l/4fb2eb4b20edcb606887ba1528d1e7f0ca27f832876ed59016bbbf08547ad493

as an invalid url (when it should not).

Thanks. Finally I sorted it our with your reminding. My code can only handle url without any routes in it. The fourth requirement of this test confuses people a little bit. It gives us an example of “https:www.example.com”. I thought we need to handle hostname of urls only.

Yesterday, I mannually tested with tens of urls and all got expected results, but none of them with routes in it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.