freeCodeCamp Challenge Guide: Create New Middleware

Create New Middleware


Problem Explanation

If you are experiencing issues with the Advanced Node and Express lessons, there are work-arounds which follow the tests, on the forum.

Relevant Links


Hints

Hint 1

The tests look for the string “Home Page” on the / route, and the string “Profile” on the /profile route.


Solutions

Solution 1 (Click to Show/Hide)
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/');
};
app.route("/").get((req, res) => {
  //Change the response to render the Pug template
  res.render(process.cwd() + '/views/pug/index', {title: 'Home page', message: 'Please login', showLogin: true});
});

app.route("/login").post(passport.authenticate('local', { failureRedirect: '/' }), (req, res) => {
  res.redirect("/profile");
});

app.route('/profile').get(ensureAuthenticated, (req,res) => {
    res.render(process.cwd() + '/views/pug/profile');
 });

Code Explanation

  • Code explanation goes here (Submit a suggestion on the forum to get your code explanation put here)