URL Shortener Microservice entering both if and else statements

I am working on the URL Shortener Microservice project (code attached below), and in my app.get function (line 93), the code inside both the if and the else statements (lines 112-118) is being executed. I’m not sure why the res.redirect() is not redirecting me to the correct website. Also, I don’t know why my project then enters the “else” section of the if/else statement after it has already been through the “if” part. Does anyone have any suggestions?

Thanks!

Here is my code:

Hello!

Your code, without modification other than the Mongo URI, works fine.

Does it show any errors on the glitch logs (Tools -> Logs, on the lower left)?

It does not show any errors in the logs. But when I change the url to include /api/shorturl/1, the console logs that it goes into both the if and the else portion, and the res.json screen portion displays the else statement’s output. I have attached a picture of my console and web view so you can see what it is doing. It never redirects me, as you can see. I think if I could fix that it may fix the problem, but I’m not sure. Do you know why this is happening? It didn’t do any of this for you?

Does the same happen if you open the page on a new window (Show -> New Window instead of Next to the Code)? I tested with both and it only works within a new window. In the Next to the code tab it doesn’t even change the page (it shows redirect on the console though).

In regards to the if statement, I don’t think it’s executing both, but since the next to the code window is calling the API on each keystroke, it may appear to be executing both.

It’s doing the same thing in the new window. It changes whatever number I enter to “undefined”.

Hmmm, that’s just weird!

Is your database being populated? There must a problem there since whenever I reload the page and add a new URL, the same ID is displayed.

Check that your database connection and/or string is correct and make sure that the records are being stored. This is my database:

I had repeats of the different short_url numbers. I think maybe they appeared because each time I edited my code “count” reset back to 1? I deleted them, and now it seems to be working fine. Thanks!!

1 Like

Ouch! I didn’t see that. Yes, that’s definitively a problem.

You could clear the collection every time the application starts or implement a counter stored on the database (a better option if we’re thinking of a production software, since deleting the database each time would break the links), either by retrieving the last inserted record or a count + 1.

1 Like