Hi! so I’m working on the url shortener project and here’s the code I’m using but i couldn’t understand why it’s not passing these tests altough it’s functional when i directely visit the app:
const express = require('express');
const cors = require('cors');
const app = express();
var bodyParser = require("body-parser");
var dns = require('dns');
app.use(bodyParser.urlencoded({extended: false}));
// 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' });
});
let httpRegex = /^https?:\/\//;
let links = [];
let id=0;
app.post("/api/shorturl", function(req, res) {
let url = req.body.url;
let withoutHTTPurl=url.replace(httpRegex, '');
dns.lookup(withoutHTTPurl, (err) => {
if(err){
return res.json({error: 'invalid url'});
}
else{
id++;
const link={original_url: url, short_url: id};
links.push(link);
return res.json(link);
}
});
});
app.get("/api/shorturl/:number", function(req, res) {
let short = req.params.number;
let link = links.find(l => l.short_url==short);
if(link){
res.redirect(link.original_url);
}
else{
res.json({error: 'url not found!'});
}
});
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});
You can POST a URL to /api/shorturl and get a JSON response with original_url and short_url properties. Here’s an example: { original_url : 'https://freeCodeCamp.org', short_url : 1}
When you visit /api/shorturl/<short_url>, you will be redirected to the original URL.
The simplest way to pass this specific test is just to check for the ftp protocol. The object the URL constructor returns also has a protocol property.
The fact that the challenge is suggesting to use dns.lookup and then passing a URL that will pass is just odd and I’m pretty sure I have commented on it before. It may be that the redirect that now happens with the john-doe.org domain didn’t always happen.
I should probably open an issue for this (I might have already, I can’t remember).