Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialOthneil Drew
22,421 PointsToo many redirects for handling error where side doesn't equal 'question' or 'answer'?
Hi, I'm trying to handle the error where if the side doesn't equal 'question' or 'answer' the application automatically redirects to show the question. However, I get an error that the server had too many redirects.
Here is my code below that results in the error:
if (!side) {
return res.redirect(`/cards/${id}?side=question`);
} else if (side !== 'question' || side !== 'answer') {
return res.redirect(`/cards/${id}?side=question`);
}
What is the correct action to avoid this?
3 Answers
James Crosslin
Full Stack JavaScript Techdegree Graduate 16,882 PointsI don't know why none of the other commenters caught this, but this conditional:
} else if (side !== 'question' || side !== 'answer') {
return res.redirect(`/cards/${id}?side=question`);
will always trigger causing a loop. The or statement makes sure of that, because side only needs to not be equal to question OR not be equal to answer. Meaning that even if it is equal to question or answer, it will not be equal to the other, and therefore the condition will be triggered as true. This could be simply solved by changing the logical or operator to a logical and operator as so:
} else if (side !== 'question' && side !== 'answer') {
return res.redirect(`/cards/${id}?side=question`);
Scott Laughead
12,750 PointsYou're likely getting caught in an infinite loop. You should add a default condition in the event that side doesn't equal "question" or "answer". So it would be something like:
if (!side) {
return res.redirect(`/cards/${id}?side=question`);
} else if (side !== 'question' || side !== 'answer') {
return res.redirect(`/cards/${id}?side=question`);
} else {
// do something
}
I would add "console.log(side);" to the else condition so you can see what the value of "side" is.
Othneil Drew
22,421 PointsThanks for answering Scott. However, I didn't get any success with this method.
korovyef
7,056 PointsI think there is an alternative solution without any if statement or redirection.
const side = req.query.side || 'question';
Here I assign the string 'question'
if the side
property of the query string is undefined
.