I am working on my url-shortener and I got it to the point where it should take a url and return either an object : {“original url”:URL} or a message {“please enter a valid url”}
however, if I pass in a url, I get an error message : Cannot GET /new/http://www.mywebsite.com
In fact, I seem to get that message whenever the “url” I pass (regardless of whether it is a url) has any forward-slashes.
What can I do?
Here is the relevant code:
app.get('/new/:url',function(req,res){
url=req.params.url;
var isUrl = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if(isUrl.test(url)){
res.json({"original url":url})
} else {
res.json("Please enter a valid url")}
});
1 Like
I used a node module
var validUrl = require(‘valid-url’);
You can see the whole code here https://github.com/Nepherius/FCC-API-Challenge/blob/master/app/routes.js#L66
Ok, thanks. I figured it out.
It wasn’t a validation problem, I just wasn’t getting the full url from the :url param. I ended up taking req.originalUrl and removing everything before the actual url. It worked.
Now all I need is a database.
1 Like
Just use mongoose, it can’t get easier than that.
I think I had the same issue with capturing the long URL in the POST call to the API. Using a star enables you to capture the full value of the parameter.
app.post("/*", (req, res) => {
const longUrl = req.params['0'];
// when calling localhost:3000/http://www.google.com
// longUrl = 'http://www.google.com'
// ...
});