URL Shortener Project help - 0

Hello Campers, im right at the start of the Api Shortener Project, im having some issues with the POST method in the index.html

So lets say i have this Form that is sent to "api/shorturl/new as a POST method

<form action="api/shorturl/new" method="POST">
          <label for="url_input">URL to be shortened</label>
          <input id="url" type="text" name="url" value="https://www.freecodecamp.org">
          <input type="submit" value="POST URL">
        </form>

Later on my server.js i catch this submit with

app.post("/api/shorturl/new",(req, res) => {
   var url=req.body.url;
});

and i need that url to be passed to the get method so i can check if this is a valid url

app.get("/api/shorturl/new/:url(*)", function(req, res) {
var url = req.params.url;
 
    if (validUrl.isUri(url)){
        console.log('Looks like an URI');
    } else {
        console.log('Not a URI');
    }

});

i think my question whould be. How can i redirect a the submit data to the appget and have them linked ?

You could use res.redirect(url) (more info here). But I’m not sure it’s a good idea. Why do you have to redirect in the first place? Why not validate the URL inside the POST method? :thinking:

Thanks @asemarian this was exactly what i was loking for.

i need the Post method workind (for functional pourposes) but this is just an REST API so it need to work directly from myApp.com/api/shorturl/new/“randomURL”

by addung this code the post method redirects the submit to the REST API so it can work it out!


app.post("/api/shorturl/new",(req, res) => {
   var url=req.body.url;
   res.redirect('/api/shorturl/new/' + url);
});

Edit

Also the FCC challange needs to test the api at /api/shorturl/new/:url(*)

1 Like