[Done] Advanced Node and Express - Set up the Environment

Not sure why I can’t get the environment to work. Here is the Glitch link.

When I run it I get the following.

// running test
error
error
error
error
// tests completed

In the .env file, I have the relevant path for
DATABASE
and a number of my choosing for
SESSION_SECRET

This is the server.js code:

'use strict';

const express     = require('express');
const session     = require('express-session');
const bodyParser  = require('body-parser');
const fccTesting  = require('./freeCodeCamp/fcctesting.js');
const auth        = require('./app/auth.js');
const routes      = require('./app/routes.js');
const mongo       = require('mongodb').MongoClient;
const passport    = require('passport');
const cookieParser= require('cookie-parser')
const app         = express();
const http        = require('http').Server(app);
const sessionStore= new session.MemoryStore();
const io          = require('socket.io')(http);

fccTesting(app); //For FCC testing purposes

app.use('/public', express.static(process.cwd() + '/public'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'pug')

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUninitialized: true,
  key: 'express.sid',
  store: sessionStore,
}));


mongo.connect(process.env.DATABASE, (err, db) => {
    if(err) console.log('Database error: ' + err);
  
    auth(app, db);
    routes(app, db);
      
    http.listen(process.env.PORT || 3000);

    //start socket.io code  

    io.on('connection', socket => {
      console.log('A user has connected');
    });

    //end socket.io code
  
  
});

When you start the provided glitch, it begins with errors and compiles to “Show off” instead of the usual “Show live”… have I missed adding something in?

Well, first thing, I don’t see where you’re loading in the .env file. I haven’t worked with glitch much, but usually .env need to be loaded - they’re not automatic. Usually you need to install a package like dotenv and then put something like require('dotenv').config() at the top of your server. Or you could write your own loader.

To confirm, I would put a console.log somewhere to check if those variables are getting loaded.

Thanks.

That would make sense but I went and checked other FCC glitch templates and none of the ones I’ve used seem to have code like that either.”

require(‘dotenv’).config() throws the error “Error: Cannot find module 'dotenv’github”

Also, file now has “Show live” as it’s status, but still runs into the same errors when I test on FCC. I’ll keep looking into it, see if there’s something else I can do to make it work.

I have the same problem…did you find a solution?

You need to add the following to your .env file and fill in the data like in the previous Advanced Node and Express challenges. For the SESSION_SECRET I just made up a number but it works (sorry for the hacky explanation):

SESSION_SECRET=
DATABASE=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=

1 Like

Yes, SESSION_SECRET is just something you make up. It is just a random string for encryption, the randomer the better.

1 Like

Thanks, but I already have all of that in the .env file. I started with:

And later added the 2 pieces of GITHUB data because the Glitch wouldn’t compile to a ‘Show LIve’ status without them.

Even so, I get the same errors when I submit the glitch.

Sorry, I guess I skimmed your post. Here’s my totally unsatisfying answer for you: NONE of the tests have passed for me for any of the Advanced Node and Express Challenges, and I’m on the third-to-last-one right now.

So I must have faulty code? No, I don’t. Other people have had similar problems, and yet for still others the tests do pass. So I don’t know.

Looking at your project, though, there is one more thing I can suggest you try. In your auth.js file, you have the following as the callback still in the strategy object: “callbackURL: “https://buttercup-delete.gomix.me/auth/github/callback””

That needs to be changed to your project callback url. Maybe that helps. If not, I think I’m out of ideas.

1 Like

No worries, I appreciate the attempt! I’m stumped.

Yeah, I had a bunch of challenges with the earlier ones too. Eventually got them all to pass up until this one, but all of the tweaks I’ve been recommended here or that I found online haven’t fixed it :confused:

I’ve re-typed two other glitches with the template, using the same code and couldn’t get them to work, so I assumed the error was in my code…

Also, I tried what you recommended regarding the callback URL, but I’m still getting the same response when I run the tests:

// running test
error
error
error
error
// tests completed

Thanks for trying to help. I appreciate it!

I just experienced some incredible serendipity and I think I just found a solution while searching for something totally different.

Add this code to the top of your server.js file and try the tests again:

const cors = require('cors');
app.use(cors());

Please let me know if it works!

Credit to hasnass for the info: Advanced Node and Express Challenges - missing stuff

EDIT: This is working for some but not all of the tests

80 Likes

AMAZING! That’s a great find @lieberscott! That solved it!
THANK YOU!!!

2 Likes

Please mark this as the answer!! Is there a place where a pull request can be made to update the glitch?

const cors = require('cors');
app.use(cors());

Thanks again!

3 Likes

yup, looks like app.use(cors()); is missing in freeCodeCamp/fcctesting.js
module.exports = function (app) {...}

12 Likes

For those of you who get here, I had to make sure I put app.use(cors()) ABOVE fccTesting(app) in order to pass the tests.

28 Likes

This made all the difference. Thanks ttstauss and everyone else.

This helped me get the tests to work. Thanks.

it’s really helped!! thank u so much !! just a little mistake … thanks again!

I’ve had the same issue with the app.use(cors()); as well.
Now I pass all the tests. However, when I try to login it comes up with “page not found”; none of my log statements actually log apart from the one inside route(’/’)
all the following don’t work

//server.js
    io.on('connection', socket => {
      console.log("io.on('connection', socket =>");
    });  

.
//auth.js: passport.use(new GitHubStrategy({
        last_login: new Date()
              },$inc:{
                  login_count: 1
              }},
              {upsert:true, new: true}, //Insert object if not found, Return new object after modify
              (err, doc) => {
                console.log("githubStrat: function(accessToken, refreshToken, profile, cb)")
                  return cb(null, doc.value);
              }
          );
.
.
.
    app.route('/auth/github/callback')
      .get(passport.authenticate('github', { failureRedirect: '/' }), (req,res) => {
          req.session.user_id = req.user.id;
          // console.log("/auth/github/callback")
          res.redirect('/views/pug/chat');
      });

Thank you. This saved me nights of sleep. Haha

The solution given above works so well that even if you don’t do anything it passes. The real thing here is if anyone got the message that a user has connected?