Ok, I seem to have this working but last test just won’t pass.
I originally done this with the npm validator package. Using validator.isUrl(), which didn’t work so tried the suggested dns.lookup method, which didn’t work. I’ve search these forums and added the regex to do two checks on the URL but still fails!
Live: https://rsheppard-url-shortener.herokuapp.com
Git: GitHub - rsheppard-dev/url-shortener
// create short url endpoint
app.post('/api/shorturl', async (req, res) => {
const url = new ShortUrl({ original_url: req.body.url })
const httpRegex = /^(http|https)(:\/\/)/
if (!httpRegex.test(url.original_url)) {
return res.status(400).json({ error: 'invalid url' })
}
const urlObject = new URL(url.original_url)
dns.lookup(urlObject.hostname, (error, address, family) => {
if (error) {
return res.status(400).json({ error: 'invalid url' })
}
})
try {
const {original_url, short_url} = await url.save()
res.status(201).json({ original_url, short_url })
} catch (error) {
res.status(400).send(error)
}
})
Sky020
June 10, 2021, 10:47pm
2
Hello there,
When I submit your app, I see a failed request:
This usually means your app is crashing
Hope this helps
1 Like
Hi,
Thank you. Urls that run through my dns.lookup test seem to crash the server. I cant workout why though?
Sky020
June 11, 2021, 10:17am
4
rsheppard83:
dns.lookup(urlObject.hostname, (error, address, family) => {
if (error) {
return res.status(400).json({ error: 'invalid url' })
}
})
Think about what you are returning here…
Add some console.log
s to see when what runs. There is a slight issue with the logic timing.
Otherwise, I also recommend you not follow good practice, and remove the .status()
responses, as this project’s tests are not set up to handle them.
Hope this helps
1 Like
Thank you so much. I made my validation into a promise and added it inside the try… catch to fix it crashing the server.
Also removing my status codes from the server made the test pass!! Thanks again!!
Could probably simplify it but it finally works. This is my new code, if it helps anyone with similar issue:
// create short url endpoint
app.post('/api/shorturl', async (req, res) => {
const url = new ShortUrl({ original_url: req.body.url })
const httpRegex = /^(http|https)(:\/\/)/
if (!httpRegex.test(url.original_url)) {
return res.json({ error: 'invalid url' })
}
const validateUrl = async () => {
return new Promise((resolve, reject) => {
const urlObject = new URL(url.original_url)
dns.lookup(urlObject.hostname, (error, address, family) => {
if (error) reject({ error: 'invalid url' })
resolve(url.original_url)
})
})
}
try {
const original_url = await validateUrl()
const { short_url } = await url.save()
res.json({ original_url, short_url })
} catch (error) {
res.send(error)
}
})
system
Closed
December 11, 2021, 5:56am
6
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.