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: