Need help with APIs and Microservices Projects - URL Shortener Microservice

Tell us what’s happening:
I tested the function of the build and it satisfies all the requirement of this question. However, I cannot pass the test . Can someone help me with it? Thank you a lot.

Your code so far
This is my repl.it project: https://repl.it/@chloechloew/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/87.0.4280.88 Safari/537.36.

Challenge: URL Shortener Microservice

Link to the challenge:

Here is my code in server.js:

'use strict';

var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');
const dns = require('dns')

var cors = require('cors');
require("dotenv").config();

var app = express();

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

/** this project needs a db !! **/ 
// mongoose.connect(process.env.DB_URI);

app.use(cors());

/** this project needs to parse POST bodies **/
// you should mount the body-parser here

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.get("/api/hello", function (req, res) {
  res.json({greeting: 'hello API'});
});


app.listen(port, function () {
  console.log('Node.js listening ...');
});

/* Database Connection */
const uri = process.env.ATLAS_URI
mongoose.connect(uri, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: false
  });
const connection = mongoose.connection;
connection.once("open", () => {
    console.log("MongoDB database connection established successfully");
  });

let urlSchema = new mongoose.Schema({
  original : {type: String, required: true},
  short: Number
})

let Url = mongoose.model('Url', urlSchema)

let bodyParser = require('body-parser')
let responseObject = {}
app.post('/api/shorturl/new', bodyParser.urlencoded({ extended: false }) , (request, response) => {
  let inputUrl = request.body['url']
  
//   let urlRegex = new RegExp(/[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi)
  
//   if(!inputUrl.match(urlRegex)){
//     response.json({error: 'invalid url'})
//     return
//   }
  
  
  dns.lookup(inputUrl, (err, addresses, family)=>{
    
    if(err){
      return response.json({error: "invalid url"})
    } else {
      responseObject['original_url'] = inputUrl
      let inputShort = 1
      
      Url.findOne({})
        .sort({short: 'desc'})
        .exec((error, result) => {
          if(!error && result != undefined){
            inputShort = result.short + 1
          }
          if(!error){
            Url.findOneAndUpdate(
              {original: inputUrl},
              {original: inputUrl, short: inputShort},
              {new: true, upsert: true },
              (error, savedUrl)=> {
                if(!error){
                  responseObject['short_url'] = savedUrl.short
                  response.json(responseObject)
                }
              }
            )
          }
  })

    }
  })

  
  

  
})

app.get('/api/shorturl/:input', (request, response) => {
  var urlInput = request.params.input;
  console.log(urlInput);
  
  Url.findOne({'short': urlInput}, (error, result) => {
      if(error) return response.send('Error reading database');

      var re = new RegExp("^(http|https)://", "i");
      var strToCheck = result.original
    if(re.test(strToCheck)){
        response.redirect(301, result.original);
    }else{
        response.redirect(301, 'http://' + result.original);
    }
  })
})

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thank you a lot about teaching me this.

Hello there,

This looks like a very similar situation to the following:
isOkay to not use dns.lookup for microservice short_url challenge? - JavaScript - The freeCodeCamp Forum

To add, I always see this when I enter a valid url:

{"error":"invalid url"}

Essentially, I suggest you look at what the dns.lookup expects as its arguments

Hint:

Not the full URL…

Hope that helps

Thank you for giving me the advice. I use the following code to strip off everything after the domain name before checking it:

let matchUrl = inputUrl.match(/https?:\/\/([^\/,\s]+\.[^\/,\s]+?)(?=\/|,|\s|$|\?|#)/g)

It still does not work :joy:

There are quite a few issues with the above RegEx:

  • / need to be escaped
  • You do not actually want to strip off \s, as the dns.lookup will catch this as invalid, and allow your code to return invalid - Do not make an invalid URL valid
  • A ? (or any quantifier) cannot be preceded by | (not quantifiable)
  • dns.lookup only expects the domain name…https is not a part of the domain.

Hope this clarifies

1 Like

Thank you very much for your advice :smile: