URL Shortener Microservice - Urls saved and tests

Hi people.

My project don’t pass second and third test but works fine for me.

I use an array to save urls instead a database like mongoose. I don’t know if its correct to pass these tests

My index.js is:

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

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

app.use(cors());

app.use('/public', express.static(`${__dirname}/public`));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/views/index.html');
});

const urls = [];

app.post('/api/shorturl', (req, res) => {
  let url = req.body.url.replace(/\/*$/, '');
  let validUrl = url.replace(/^https:\/\/(www.)?/, '');
  dns.lookup(validUrl, (err, address, family) => {
    if (err) {
      res.json({ error: 'invalid url' })
    }
    else {
      if (!urls.includes(url)) {
        urls.push(url);
      }
      res.json({
        original_url: url,
        short_url: urls.indexOf(url) + 1
      });
    }
  });
});

app.get('/api/shorturl/:id', (req, res) => {
  const externarlUrl = urls[req.params.id - 1];
  res.redirect(externarlUrl);
});

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

I changed the name of sample.env file to .env and I deployed the project on Vercel.

1 Like

I’d suggest you create a Replit with your code when asking for help as it makes it easier to help.


Your URL validation is not working as expected. dns.lookup takes a hostname. You can use the URL constructor to get the hostname.

const invalidURL = "ftp:/john-doe.invalidTLD";
const validURL = "https://boilerplate-project-urlshortener.username.repl.co/?v=1666992293943";

console.log(new URL(invalidURL).hostname); // john-doe.invalidTLD
console.log(new URL(validURL).hostname); // boilerplate-project-urlshortener.username.repl.co

When doing the submission have the network tab open in the browser so you can inspect the request/response and payload.

2 Likes

Thanks for your help.

I changed how get urls but still no passing tests. I cannot detect where is the problem.
Network tab confuse me.

Here is my project:
https://replit.com/join/aglwtmmsuu-gabit690

You need to respond with the original URL req.body.url, not url.origin (and add it to the array).

Log them out inside the handler to see the difference.

let url = new URL(req.body.url);
console.log('req.body.url', req.body.url)
console.log('url.origin', url.origin)
3 Likes

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