URL Shortener Microservice problem with passing tests

Hello campers.
I have an issue with this project. Although my project works as it should i can’t pass test 2 and test 3. I return json like this {"original_url":"https://freeCodeCamp.org","short_url":"JSytVEpZL"} on the link /api/shorturl. And redirect on the site if i go /api/shorturl/JSytVEpZL. I have all instances in my MongoDB Cluster
Link to my project https://replit.com/@RomanMarchuk1/boilerplate-project-urlshortener-2#server.js
Here is server.js

require('dotenv').config();
const express = require('express');
const shortId = require("shortid")
const validUrl = require("valid-url")
const cors = require('cors');
const dns = require("dns")
const app = express();
const mongoose = require("mongoose")

const mySecret = process.env['newMONGO_URI']

mongoose.connect(mySecret, { useNewUrlParser: true, useUnifiedTopology: true })
console.log("mongoose connection state:" + mongoose.connection.readyState)
const Schema = mongoose.Schema
const mySchema = new Schema({
  urlCode:{type:String, required:true},
  url:{type:String, required:true},
  
})
let MyUrl1 = mongoose.model("MyUrl1", mySchema)


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

app.use(cors());

app.use('/public', express.static(`${process.cwd()}/public`));
app.use(express.urlencoded({ extended: true }))
app.get('/', function(req, res) {
  res.sendFile(process.cwd() + '/views/index.html');
});

// Your first API endpoint
app.post("/api/shorturl", (req, res)=>{
   let urlId = shortId.generate() 
   const hostname = req.body.url.replace(/https?:\/\//, "");
   dns.lookup(hostname, (err, adr, fam)=>{
       if(err){
         res.json({ error: 'invalid url' })
       }
       else{
          try{res.json({original_url:req.body.url, short_url:urlId})
    let newUrl = new MyUrl1({
       urlCode:urlId,
       url:req.body.url
    })
    newUrl.save()} catch(err){
     console.error(err)
    }
          
       }
       
   })
  

})
app.get("/api/shorturl/:shortUrl", async (req, res)=>{
  try{
    const urlParam = await MyUrl1.findOne({urlCode:req.params.shortUrl})
    if (urlParam){
    return res.redirect(urlParam.url)
  }
  else{
    return res.status(404).json("No URL Found")
  }
  }catch(err){
    console.log(err)
    res.status(500).json("Server Error")
  }
  
  })



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/90.0.4430.93 Safari/537.36.

Challenge: URL Shortener Microservice

Link to the challenge:

Welcome to the forums @maroma1991. It would be easier to debug if you could post a link to your project on repl.it or a similar platform so we could play with the code directly.

Regardless, the best thing to do when you encounter an error like this is to insert logging statements of your route input and output (at all responses) for the failing routes to make sure that you are receiving and sending the information you think you are receiving and sending.

Just looking I am very suspicious of this code

which is sending the JSON response before the database processing. So if the DB stuff fails, the response is already sent and the caller may have bad information. It is usually better to do all the processing, construct the response JSON and then use something like return res.json(obj) so that you are returning the finished product and you know that the route is terminating.

Thank you for your feedback, link to my project here https://replit.com/@RomanMarchuk1/boilerplate-project-urlshortener-2#server.js

Just like I said, logging the inputs and output tells the tale:

POST url:  {
  url: 'https://[...].repl.co/?v=1620408372960'
}
{ error: 'invalid url' }

Your code in the POST route is not validating that URL correctly and is always returning the error message. You have to handle the URL assuming it may have a protocol, a host, and route parameters.

I changed my POST, now i pass test 2 and 3, but don’t pass test 4 If you pass an invalid URL that doesn't follow the valid http://www.example.com format, the JSON response will contain { error: 'invalid url' }
When i test it myself, with random inputs i have this JSON response, but still not pass test 4

app.post("/api/shorturl", (req, res)=>{
   let urlId = shortId.generate() 
   if (validUrl.isUri(req.body.url)){ 
     const urlObject = new URL(req.body.url)
    dns.lookup(urlObject.hostname, (err, adr, fam)=>{
       if(err){
         return res.json({ error: 'invalid url' })
       }
       else{
          try{res.json({original_url:req.body.url, short_url:urlId})
    let newUrl = new MyUrl1({
       urlCode:urlId,
       url:req.body.url
    })
    newUrl.save()} catch(err){
     console.error(err)
    }
          
       }
       
   })
   }
   else{
     res.json({ error: 'invalid url' })
   }
   
  

})

I fix problem using regexp for validating url, thanks for help

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