Advanced Node and Express - Communicate by Emitting Your client is listening for 'user count' event

var currentUsers = 0;     
 io.on('connection', socket => {
  console.log('A user has connected');      
    currentUsers++;
          io.emit('user count', currentUsers); 
           socket.on('user count', function(data){
  console.log(data);
});       
});


I also tried the glitch from challenge and got all errors. I laso copied the env. variables



I also try
ttp.listen(process.env.PORT || 3000, () => {
console.log("Listening on port " + process.env.PORT); });

var currentUsers = 0; 
      //start socket.io code  
      io.on('connection', (socket) => {
             console.log('A user has connected');  
             ++currentUsers;
           
             socket.on('user count', function(data){ 
               io.emit('user count', currentUsers);  
             console.log(data);
            });     
         socket.on('disconnect', (user) => {
        io.emit('disconnect', user);
        console.log(socket.name + ' has left the chat.');
    });

    });

Did you solve this yet? The socket.on… should be in the client.js file, and should NOT include io.emit within. io.emit should within io.on()…

13 Likes

I started from scratch but even worse all error

Did you remember to fill in the .env file?

Another common issue that it could be, is for the testing to work you need to add app.use(cors()). I did this in the fcctesting.js file within the export. This allows them to run tests remotely against your code. For some reason some of the challenges weren’t set up correctly and so they have the cors dependency installed, and required in the file, but they aren’t using it.

8 Likes

I try and I really fil the nev. without the logs have errors.


I dont remeber what was on original, but form me is suspisious
app/auth.js
there is db.collection(‘chatusers’).findOne(
I am no suer if there sould user or socialuser?
Finally I look in developer mode and it was not allowed origin and I compare the files and that from exercise was wrong

 var allowedOrigins = ['https://pricey-hugger.gomix.me', 'http://pricey-hugger.gomix.me', 'https://f.. '
replace by
const allowedOriginsMatcher = /^https?:\/\/([\w-]+\.)*freecodecamp\.org/;

and

 app.use(function (req, res, next) {
    const origin = req.get('origin');
    if(allowedOriginsMatcher.test(origin)) {
      res.setHeader('Access-Control-Allow-Origin', origin);
    }
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
  });
2 Likes

This was the answer that fixed it for me.

3 Likes

Thanks - that was helpful.

Thanks, it was the reason why I was facing that error

Thanks for your post, it help me finally pass that test, regarding the origin errors

const allowedOriginsMatcher = /^https?:\/\/([\w-]+\.)*freecodecamp\.org/;

 app.use(function (req, res, next) {
    const origin = req.get('origin');
    if(allowedOriginsMatcher.test(origin)) {
      res.setHeader('Access-Control-Allow-Origin', origin);
    }
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
  });

this actually help thanks

Thank you, you solve my problem

You saved me again! I’ve been seriously struggling through this certificate. It has been made with so many errors, ambiguous instructions, and incomplete information; it’s quite ridiculous really in comparison to the other certificates. Thanks to you, I’m actually getting through this.

Mine is not passing the test. Any pointer to what the problem could be?
Please see glitch file here https://magic-sudden-handle.glitch.me

Also here is my server 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);
const cors = require("cors");
const passportSocketIo = require("passport.socketio");
require("dotenv").config();

fccTesting(app); //For FCC testing purposes
app.use(cors());
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.use(
    passportSocketIo.authorize({
      cookieParser: cookieParser,
      key: "express.sid",
      secret: process.env.SESSION_SECRET,
      store: sessionStore
    })
  );

  io.on("connection", socket => {
    var currentUsers = 0;
    ++currentUsers;
    socket.on("user count", function(currentUsers) {
      io.emit("user count", {
        currentUsers: socket.request.currentUsers
      });
    });
    console.log(currentUsers);

    io.emit("user", {
      name: socket.request.user.name,
      currentUsers,
      connected: true
    });

    socket.on("chat message", function(data) {
      io.emit("chat message", {
        name: socket.request.user.name,
        message: data
      });
    });
    console.log("user " + socket.request.user.name + " connected");

    socket.on("disconnect", () => {
      currentUsers -= 1;
      io.emit("user", {
        name: socket.request.user.name,
        currentUsers,
        connected: false
      });
      console.log("user " + socket.request.user.name + " disconnected");
    });
    
  });

  //end socket.io code
});


and t code on fcctesting

'use strict';

const fs = require('fs');
const cors = require('cors');

module.exports = function (app) {
  
  app.use(function (req, res, next) {
      const allowedOriginsMatcher = /^https?:\/\/([\w-]+\.)*freecodecamp\.org/;
       var origin = req.headers.origin;
        if(allowedOriginsMatcher.test(origin)) {
      res.setHeader('Access-Control-Allow-Origin', origin);
    }
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
  });
  
  app.route('/_api/server.js')
    .get(function(req, res, next) {
      console.log('requested');
      fs.readFile(process.cwd() + '/server.js', function(err, data) {
        if(err) return next(err);
        res.send(data.toString());
      });
    });
    
  app.route('/_api/package.json')
    .get(function(req, res, next) {
      console.log('requested');
      fs.readFile(process.cwd() + '/package.json', function(err, data) {
        if(err) return next(err);
        res.type('txt').send(data.toString());
      });
    });

  app.get('/_api/app-info', function(req, res) {
    var hs = Object.keys(res._headers)
      .filter(h => !h.match(/^access-control-\w+/));
    var hObj = {};
    hs.forEach(h => {hObj[h] = res._headers[h]});
    delete res._headers['strict-transport-security'];
    res.json({headers: hObj});
  });
  
};

Hi everyone! My solution was just adding:

app.use(cors());

inside the module.exports variable (on line 41) of the fcc testing file.

Hope this helps!

Thank you. That solved my problem too.