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?
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.
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.