Back End Development and APIs Projects - URL Shortener Microservice - Test 2 & 3 not passing

Tell us what’s happening:
Hello everyone, I can’t find to figure out why tests 2 and 3 are not passing, the behavior is the expected one according to the requirements.

For example on #2 my input is https://boilerplate-project-urlshortener.derjuniorcoder.repl.co/api/shorturl/2, this ones gives me the right json object with the right params.

In number 3 if i enter on the url bar if I enter the same input https://boilerplate-project-urlshortener.derjuniorcoder.repl.co/api/shorturl/2 it takes me to the main page of Freecodecamp.

Validation test is OK, would love any hint as this is the first project I have to ask for help in here. One last thing, I get my urls from a bidimensional array, thanks.

Here is my code, so far

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

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

app.use(cors());

app.use('/public', express.static(`${process.cwd()}/public`));

app.use(bodyParser.urlencoded({ extended: false }));

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' });
});

const urls = ["https://www.google.com/", "https://www.freecodecamp.com",
  "https://www.yahoo.com", "https://www.twitter.com/", "https://www.youtube.com/"];

// ou can POST a URL to /api/shorturl and get a JSON response with original_url and short_url properties
app.post("/api/shorturl", (req, res) => {
  let url = req.body.url;
  let valid = new URL(url);
  let validUrl = valid.hostname;

  dns.lookup(validUrl, (err, address, family) => {
    console.log("err: " + err);
    if (err) {
      res.json({
        error: "invalid url"
      });
    } else {
      const regex = /\d+$/g;
      const shortURL = req.body.url.match(regex);
      console.log(shortURL[0]);
      res.json({
        original_url: urls[parseInt(shortURL[0]) - 1],
        short_url: parseInt(shortURL[0])
      });
    }
  });

});

// When you visit /api/shorturl/<short_url>, you will be redirected to the original URL.
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}`);
});

Your project link(s)

solution: boilerplate-project-urlshortener - Replit

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: Back End Development and APIs Projects - URL Shortener Microservice

Link to the challenge:

Log your route inputs and all responses for both routes and then run the fCC tests. You’ll get output like

POST URL
req.body: {"url":"https://boilerplate-project-urlshortener.jeremyagray.repl.co/?v=1683251504125"}
req.params: {}
req.query: {}
err: null
1683251504125
{ original_url: undefined, short_url: 1683251504125 }
GET URL
req.body: {}
req.params: {"id":"1683251504125"}
req.query: {}
redirecting to undefined

for the failing tests.

I really can’t tell what you’re trying to do in the POST route, but you need to be using a database of some kind to persist URL data (like MongoDB as in the practice exercises) and not using any predefined URL data 9your code has to POST and GET data, so you can load test data via POST without predefining it). As is clear from the logged output, you can’t get useful URL information by matching digits in the URL (Are you tryin to get the request parameters available through req.params?). These tests use generated URLs so you have to be able to handle any URL in general.

Logging is critical. Try logging every step of the process to see how the routes do every step while you’re running the fCC tests.

Thank you very much for your help, this was more of an understanding what does the project has to do than coding the right way, I didn’t know that I had to load the data to the database via POSTing it, like you said, so basically the trick in here was to load an url and assign it a number, then when I entered that number on the address bar it would lead me to that site via the short_url parameter.

I still appreciate a lot you taking your time to reading my problem.

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