Other than the code below, all from gh repo is unchanged:
// ...
const bodyParser = require('body-parser')
const dns = require('dns')
// ...
app.use(bodyParser.urlencoded({ extended: false }))
let urls = []
// Verify URL and to array and return it with a short url (int)
app.post('/api/shorturl', (req, res) => {
const url = req.body.url
const host = url.replace(/^.*?:\/\//, '')
dns.lookup(host, (err) => {
if (err) return res.json({ error: 'invalid url' })
urls.push(url)
res.json({
original_url: url,
short_url: urls.length
})
})
})
// Access the URL via it's index in array
app.get('/api/shorturl/:n', (req, res) => {
res.redirect(urls[req.params.n - 1])
})
// ...
The code works in the I can enter https://www.google.com
and get the response {"original_url":"https://freeCodeCamp.org","short_url":1}
. I can then go to the address bar and type http://localhost:3000/api/shorturl/1
and am redirected to freeCodeCamp’s website. I can then go back and type https://freeCodeCamp.org
and get the response {"original_url":"https://www.google.com","short_url":2}
. In the address bar I can enter http://localhost:3000/api/shorturl/2
and am taken to Google’s website. Finally, I can enter ftp:/john-doe.invalidTLD
and get the response {"error":"invalid url"}
. This is the extent of the testing. However, it fails both tests two and three:
You can POST a URL to
/api/shorturl
and get a JSON response withoriginal_url
andshort_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.
In this case the test seems wrong because I can POST a url to /api/shorturl
and do get a JSON response with original_url
and short_url
properties; likewise, I am redirected to the original URL when I visit /api/shorturl/<short_url>
.