Not passing invalid URL test

Tell us what’s happening:
I have completed the challange based on a youtube walkthrough, after failing some time with other solutions and their documentations. This solution seems to give back all the proper responses, however FCC doesn’t seem to accept the JSON response for invalid URLs.

I tried to modify the text of the error message, but it seems there is another problem. Could anyone recommend something how to solve this?

Here is my server.js:
Your code so far

'use strict';

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



// 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}`);
});

// connect  to mongoDB
const uri = process.env.MONGO_URI;
mongoose.connect(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverSelectionTimeoutMS: 5000
});

const connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error: '));
connection.once('open', () => {
  console.log("MongoDB connection successful.");
});


//define url schema and model
let urlSchema = new mongoose.Schema({
  original_url: {type: String, required: true},
  short_url: Number
});

let urlModel = new mongoose.model('URL', urlSchema);

// Get the input URL
let responseObj = {};

app.post('/api/shorturl/new', bodyParser.urlencoded({ extended: false }), (req, res) => {
  let inputUrl = req.body.url;
  
  //check validity of 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)) {
    res.json({error: 'Invalid URL'});
    return
  }
  
  responseObj['original_url'] = inputUrl;
  
  let inputShort = 1;
  
  urlModel.findOne({}).sort({short_url: 'desc'}).exec((err, result) => {
    if(!err && res != undefined) {
      inputShort = result.short_url + 1;
    }
    if(!err) {
      urlModel.findOneAndUpdate(
        {original_url: inputUrl},
        {original_url: inputUrl, short_url: inputShort},
        {new: true, upsert: true},
        (err, savedUrl) => {
          if(!err) {
            responseObj['short_url'] = savedUrl.short_url;
            res.json(responseObj);
          }
        }
      );
    }
  });
  
  //res.json(responseObj);
});


app.get('/api/shorturl/:input', (req, res) => {
  let input = req.params.input;
  
  urlModel.findOne({short_url: input}, (err, result) => {
    if(!err && result != undefined) {
      res.redirect(result.original_url)
    } else {
      res.json('URL not found')
    }
  });
});

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

Challenge: URL Shortener Microservice

Link to the challenge:

Hello @dzsamboki.techwriter
Is URL validation correct? Have you tested it? If the validation is correct, the problem is with the message I guess. Try this

res.json({error: 'invalid url'});

that’s the way it’s written in the test. Letter case does matter when it comes to thee tests.I hope this solves your problem.

I tried that as well, here on Glitch I get back the proper result, but it doesn’t pass the FCC test for some reason.

My glitch instance:
https://fcc-urlshortener-dzsamboki.glitch.me

My glitch project:
https://glitch.com/edit/#!/fcc-urlshortener-dzsamboki

I passed http://www.example.com as the URL which is invalid but the server is returning the response as if it’s a valid URL. There’s a problem with validation I guess

Ohh, I will try to modify the RegEx then, the challange specification is a bit ambigious in this case, I assumed that ‘http’ is also an acceptable format.

Just checked the instance provided in the challange description (https://url-shortener-microservice.freecodecamp.rocks/) and it also accepts the http://www.example.com

The validity of the test means that it should be a valid registered domain. You can use dns.lookup() for checking the validation of the url. It goes something like this

  dns.lookup(<replace URL to check here>, (err) => {
    if (err) return // handle error
    else {
      // save the info to database
      })
    }
  })

remeber the url should be like this www.example.com not like this http://www.example.com.

1 Like

My mistake. It is valid. When you run the fcc tests, it passes the invalid url to check whether your code is validation url or not. Try putting those urls explicitely.

1 Like

Will check this also, now I found a better RegEx somewhere on StackOverflow:

let urlRegex = new RegExp(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/gi);
  
  if(!inputUrl.match(urlRegex)) {
    return res.json({error: 'invalid url'});
    
  }

With this it passes the invalidity test as well.
But checking with the dns.lookup() looks more sophisticated in this case, so I will definitely look into it.

Thanks for your tips!!

Blockquote

Look into it and if it still doesn’t work, I am here to help.

1 Like