Problem with POST method for for saving form info to database for the URL shortener Microservice project

I seem to be having a fundamental problem with the post method. The project is using node.js, mongodb, mongoose, and express. Full code here on glitch.

When I click “POST URL” on my site (which also has the details required for the project) I get the message “Cannot POST /api/shorturl/new”.

I’m not sure where the problem in my code is. I wish I could narrow it down but I’m lost trying to get app.post to work

var createNewShortUrlDocument = function(url) {
    var record = new ShortUrl({original_url: url, 
                               short_url: ShortUrl.length + 1});
    console.log(record);
    record.save(function (err, record) {
      if (err) {
        console.log(err);
        } else {
          console.log("Record Saved");
        }
    });
};

app.post("api/shorturl/new", function(req, res, next) {
  var url = req.body.url;
  console.log(url);
  
  var findOriginalUrl = function(originalUrl) {
    ShortUrl.findOne({original_url: originalUrl}, function(err, doc) {
        if (err) {
            console.log(err);
        } else {
            if (doc !== null) { //if url found send url and short url
                res.json({doc});
            } else {
                createNewShortUrlDocument(originalUrl); //if not found add to database
            }
        }
    })
  };
  
  dns.lookup(url, function(err) {  //check for valid url
    if (err) {
      res.json({"error": "invalid URL"});
    } else {
      findOriginalUrl(url); //check to see if url exists in database
    }
  })
});

Did you try putting a forward slash:

app.post("/api/shorturl/new", function(req, res, next) {

1 Like

@JohnnyBizzel Thanks! I knew it was something simple but I just didn’t see it. Now I have to get the dns.lookup function to work because i get {“error”:“invalid URL”} which means there is an error with this function :frowning: Now I’ll remember that forward slash :slight_smile:

1 Like

I didn’t do a DNS lookup when I did this challenge. Is this a new requirement?

I’m not sure if a DNS lookup is required to pass the challenge but the URL has to be a valid format - and I saw some people use a regex to test the format. However, they give a hint to use dns.lookup:
" 2. If I pass an invalid URL that doesn’t follow the valid http(s)://www.example.com(/more/routes) format, the JSON response will contain an error like {"error":"invalid URL"} . HINT : to be sure that the submitted url points to a valid site you can use the function dns.lookup(host, cb) from the dns core module."

I’m going to try it without to make sure the rest of my code works and then see if I can implement dns.lookup.

1 Like