URL Shortener Microservice - Problem with 'invalid url'

Tell us what’s happening:
In the URL Shortener Microservice project, I am facing a problem with passing the last test, which reads the following:
" 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' }"

With my existing code, I am seeing {“error”: “Invalid URL”} when I insert a wrong URL.


However, for some unknow reasons, I can’t manage to pass the test. I don’t see any error at the Glitch debugger.

Your code so far
Here are my codes in server.js:

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
var mongoose = require('mongoose');

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

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

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

// Database Connection
let uri = 'mongodb+srv://user1:' + process.env.PW + '@cluster0.htisd.mongodb.net/db1?retryWrites=true&w=majority'
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });





// Creating the URL model
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
  }
    
  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) => {
  let input = request.params.input
  
  Url.findOne({short: input}, (error, result) => {
    if(!error && result != undefined){
      response.redirect(result.original)
    }else{
      response.json("invalid url")
    }
  })
})

How can I fix the issue?

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:

Hello there,

Notice here:

 }else{
      response.json("invalid url")
    }

You are not returning what is expected:

JSON response will contain { error: 'invalid url' }

There is likely more useful information in the console of the browser, when you submit on the freecodecamp.org page.

Otherwise, please provide a link to your project code, if you do not mind.

Hope this helps

Here is the link to my codes: https://glitch.com/edit/#!/freecodecamp-url-shorte-ehsanul

Hey,

The test looks like this:

async (getUserInput) => {
  const url = getUserInput('url');
  const res = await fetch(url + '/api/shorturl/new/', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: `url=ftp:/john-doe.org`
  });
  if (res.ok) {
    const { error } = await res.json();
    assert.isNotNull(error);
    assert.strictEqual(error.toLowerCase(), 'invalid url');
  } else {
    throw new Error(`${res.status} ${res.statusText}`);
  }
};

freeCodeCamp/url-shortener-microservice.md at master · freeCodeCamp/freeCodeCamp (github.com)

This means there is an error in the app, which is causing it not to return an error, when it should

The best way to test this is with a tool like POSTMAN, where you can make the POST request to your app, and see the responses the same way the tests do.

I can pass the final test by using this line:
let urlRegex = new RegExp(/^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+(\.[a-z]{2,}){1,3}(#?\/?[a-zA-Z0-9#]+)*\/?(\?[a-zA-Z0-9-_]+=[a-zA-Z0-9-%]+&?)?$/)
However, If I use the above line, the second and third tests are not passed. It’s a pretty strange issue!

Remember, all the regex needs to be able to do is tell whether or not the URL starts with http/https.

Finally, I have found the solution. I just need to replace the previous regex with this line:
let urlRegex = new RegExp (/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi)

Glad you got it working.

Just to show what I was getting at, this is all you need:

/(?<=(http|https):\/\/)[^\/]+/
1 Like