'Modules should be present' Error

Tell us what’s happening:

Your project link(s)

solution: https://boilerplate-advancednode.danielbenedictb.repl.co

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36.

Challenge: Clean Up Your Project with Modules

Link to the challenge:

I have been searching forums and trying their solutions but to no avail. I have also tried direct copy and paste other developers’ work but it would still fail the test. I also tried with and without .js extension in requiring on auth and routes. I have been at this for quite a while now and I decided to ask for help on this forum. When I console.log the test from FCC it only shows that it is trying to access server.js. My guess is it’s not moving forward with the test that reaches /_api/auth.js and /_api/routes.js. I am currently using my code on replit. Any help is highly appreciated. Thank you in advance.

Here is my code.

server.js

'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');

const session = require('express-session')
const passport = require('passport')
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb').MongoClient;
const LocalStrategy = require('passport-local');
const bcrypt = require('bcrypt');
const routes = require("./routes.js");
const auth = require("./auth.js");

process.env.SESSION_SECRET = 10;

//process.env.MONGO_URI  not shown here but present in my actual code
//process.env.DB_NAME not shown here but present in my actual code

const app = express();

app.set('view engine','pug');
app.set('views', './views/pug')

//For FCC testing purposes
fccTesting(app); 
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

mongo.connect(process.env.MONGO_URI, {useUnifiedTopology: true, useNewUrlParser: true}, function(err, db){

  if (err) return console.log(err);
  var dbase = db.db('advancednode');
  console.log('Successful database connection');

  routes(app, dbase, passport, bcrypt);
  auth(app, dbase, session, passport, ObjectID, LocalStrategy, bcrypt); 
 
});

auth.js

module.exports = function (app, db, session, passport, ObjectID, LocalStrategy, bcrypt) {

  app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
  }));

  app.use(passport.initialize());
  app.use(passport.session());  

  passport.serializeUser(function(user, done){
    done(null, user._id);
  });

  passport.deserializeUser(function(id, done){
    db.collection('users').findOne({_id: new ObjectID(id)}, function(err, doc){
      if (err) return console.log(err);
      done(null, doc);
    })
  });

  passport.use(new LocalStrategy(
  function(username, password, done) {
    db.findOne({ username: username }, function (err, user) {
      console.log('User '+ username +' attempted to log in.');
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!bcrypt.compareSync(password, user.password)) { 
        return done(null, false);
      }

    });
  }
  ));
  
}

routes.js

module.exports = function (app, db, passport, bcrypt) {

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log('Listening on port ' + PORT);
});  

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
    // showLogin tells pug to show login form
    res.render('index', {
      title: 'Connected to Database',
      message: 'Please login',
      showLogin: true,
      showRegistration: true
    });
  });

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

  app.route('/register')
  .post((req, res, next) => {
    const hash = bcrypt.hashSync(req.body.password, 12);
    db.findOne({ username: req.body.username }, function(err, user) {
      if (err) {
        next(err);
      } else if (user) {
        res.redirect('/');
      } else {
        db.insertOne({
          username: req.body.username,
          password: hash
        },
          (err, doc) => {
            if (err) {
              res.redirect('/');
            } else {
              // The inserted document is held within
              // the ops property of the doc
              next(null, doc.ops[0]);
            }
          }
        )
      }
    })
  },
    passport.authenticate('local', { failureRedirect: '/' }),
    (req, res, next) => {
      res.redirect('/profile');
    }
  );

  app.route('/profile').get(ensureAuthenticated, (req,res)=>{
      res.render('profile', {
        username: req.user.username
      });  
  })

  app.route('/logout')
  .get((req, res) => {
    req.logout();
    res.redirect('/');
  });

  app.use((req, res, next) => {
  res.status(404)
    .type('text')
    .send('Not Found');
  });

}

Hello there,

You cannot set env variables reliably like this, because they are cross-script.


You must use this function the way it was presented. Otherwise you will get unexpected results.

I suggest you recopy the given solution for this step, and try again. If that still does not resolve it, then just mention it here, and I will take another look from the expected stand point.

1 Like

Thank you for this.

My reasoning for declaring .env variables like this was that, I forked this directly from FCC but I could not find the file itself, save for the sample.env. I guess I will just redirect the path of dotenv to sample.env since replit wont allow me to create a new one.

As for the case of myDB, other solutions that I found did not resort to use this module and it passed the test. So I figured I should give it a shot for a while.

I’ll try your method as soon as I can. I only have a few hours a day to study coding since I have a 9-5. I get back to this thread to share my results.

Thank you once again.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.