Node.js console.log not logging in terminal - node.js

I have a simple app where I'm trying to log to the console (terminal where I started Node, not the the browser console). Express seems to execute the route since I can see the response in my browser.
Also the logging in the app.listen(..) seems to work, but I don't see any logs afterwards.
'use strict';
// 3rd-party dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const dbSetup = require('./db-setup');
// Application config
const LOCAL_APP_PORT = 8080;
const PUBLIC_APP_PORT = process.env.PUBLIC_APP_PORT || LOCAL_APP_PORT;
global.dbType = process.env.DB_TYPE;
// Sanity check for debugging
console.log("local app port:", LOCAL_APP_PORT);
console.log("public app port:", PUBLIC_APP_PORT);
console.log("db type:", global.dbType);
// Database setup for either MongoDB or Postgres
dbSetup(global.dbType);
// Express middleware
app.use(bodyParser.json()); // for parsing application/json
// Import routes
//const index = require('./routes/index');
//const owner = require('./routes/owner');
//const shop = require('./routes/shop');
//const product = require('./routes/product');
// Set up express routes
app.use('/',(req,res,next) => {
console.log("This is not showing on the terminal.");
res.send("This is sent to the browser");
next();
})
//app.use('/owner', owner);
//app.use('/shop', shop);
//app.use('/product', product);
app.listen(LOCAL_APP_PORT, () => {
console.log('App started ...');
});
EDIT: Solved. Problem was my app was basically available on two ports at the same time. One the the public port however it was not showing any logs...
Terminal screenshot

Related

Passing an object from a main server.js file down to a controller

I'm making a basic restaurant ordering web app for fun/learning purposes using node/express for my backend and react as my frontend. I've based my app on a mix of various YT tutorials including the ones Dave Gray to structure my project.
Currently I'm at the stage where I'm trying to implement notifications using SocketIO (the idea that the server will push notifications down to the clients to notify them of certain events such as an order being made).
My current progress is here: https://github.com/kevin-rph-lee/noodlebox/tree/socket-notifications
The issue I'm having is I'm trying to figure out the best way to pass my SocketIO object down to one of my controllers (specifically the orders controller).
My current structure is:
server.js --> orders.js (route) --> ordersController.js (controller)
Currently in my main server.js file I have initialized the io object for SocketIO (as seen below)
require('dotenv').config();
const WebSocketServer = require("ws").Server
var http = require("http")
const express = require('express');
const path = require('path');
const PORT = process.env.PORT || 3001;
const app = express();
const morgan = require('morgan');
const cors = require('cors');
const corsOptions = require('./config/corsOptions');
const credentials = require('./middleware/credentials');
const cookieParser = require('cookie-parser');
// Creating a new socketio server
const server = require('http').createServer(app);
const io = require('socket.io')(server);
//Numbers of users connected. Initially 0
let clientsConnected = 0
io.on('connection', function(socket){
//Client connecting, incrementing client counter
clientsConnected++
console.log('Client connected. Total clients connected ' + clientsConnected)
//When a message is recieved from a client, echo it to all other clients connected
socket.on("message from client", (arg) => {
console.log('reieved')
console.log(arg)
// socket.broadcast.emit('message to client', arg)
// socket.to(1).emit('message to client', 'enjoy the game')
io.in(1).emit('message to client', 'enjoy the game')
});
socket.on("join", (userID) => {
socket.join(userID)
console.log('Rooms:')
console.log(socket.rooms)
});
socket.on("leave", (userID) => {
socket.leave(userID)
console.log('Rooms:')
console.log(socket.rooms)
});
//Deincrement the counter when the client disconnects
socket.on("disconnect", (reason) => {
clientsConnected--
console.log('Client connected. Total clients connected ' + clientsConnected)
});
})
// PG database client/connection setup
const { Pool } = require('pg');
const dbParams = require('./lib/db.js');
const db = new Pool(dbParams);
db.connect();
// Load the logger first so all (static) HTTP requests are logged to STDOUT
// 'dev' = Concise output colored by response status for development use.
// The :status token will be colored red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes.
app.use(morgan('dev'));
app.use(credentials);
app.use(cors(corsOptions));
app.use(express.json()); // => allows us to access the req.body
//middleware for cookies
app.use(cookieParser());
if (process.env.NODE_ENV === 'production') {
//server static content
//npm run build
app.use(express.static(path.join(__dirname, 'client/build')));
}
console.log(__dirname);
console.log(path.join(__dirname, 'client/build'));
// Separated Routes for each Resource
const usersRoutes = require('./routes/users');
const refreshRoutes = require('./routes/refresh');
const menuItemsRoutes = require('./routes/menuItems');
const ordersRoutes = require('./routes/orders');
// Resource routes
app.use('/users', usersRoutes());
app.use('/refresh', refreshRoutes());
app.use('/menuItems', menuItemsRoutes());
app.use('/orders', ordersRoutes());
// All other GET requests not handled before will return our React app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '/client/build/index.html'));
});
server.listen(PORT);
I am now trying to figure out how to pass the io object down to my orders route, and then from the route to the controller.
Within server.js, to pass io down to the route it was thinking it would be something like...
app.use('/orders', ordersRoutes(io));
But within the order route itself I get stuck
order.js
const express = require('express');
const router = express.Router();
const ordersController = require('../controllers/ordersController')
const verifyJWT = require('../middleware/verifyJWT')
const verifyRoles = require('../middleware/verifyRoles');
module.exports = () => {
//Get order
router.route('/')
.get(verifyJWT, verifyRoles('user', 'admin'),ordersController.getOrders)
//Create order
router.route('/')
.post(verifyJWT, verifyRoles('user', 'admin'), ordersController.createOrder)
return router;
};
To receive the io object from server.js I'm thinking I would need to modify the module.exports line so it would look like:
module.exports = (io) = {
but at that point I'm stuck on how I can pass it down one more layer from the route file to the controller file. The idea is I want the io functionality (e.g broadcasting a SocketIO message) to be available to me within the controllers file. In particular I want the ability to broadcast a message when a certain axios request is made from a connected client (e.g broadcast a SocketIO message when an axios POST request is made to create an order).
I was hoping someone could help me out with a potential way to move forward, or let me know if I'm going down the completely wrong path.
Thank you

How to load mongodb URI from .env file on heroku?

I am a beginner to MERN stack and I deployed my nodejs app to heroku but the app is unable to connect to mongodb atlas and data from the database does not load when I give the mongodb uri via an environment variable.It works fine when I directly give the uri via a variable.Also when run locally,the app connects to atlas without any problem using environment variable.Any idea why its not working on heroku and how to fix it?
server.js
const express = require('express'); //nodejs framework for creating web apps
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');
require('dotenv').config(); //for setting environment variables on server
const app = express(); //creating the app
//Serve static assets if in production
if(process.env.NODE_ENV ==='production'){
//Set static folder
app.use(express.static('client/build'));
app.get('*',(req, res) => {
res.sendFile(path.resolve(__dirname,'client','build','index.html'));
});
}
////////////////////////////////////////
const port = process.env.PORT || 5000;
app.use(cors()); //for cross origin resource sharing ie.cross domain requests
app.use(express.json()); //for handling json data
const uri = process.env.ATLAS_URI;
//its works fine when I give it as below
//const uri="mongodb+srv://jose:<password>#exercisecluster-rmqkg.gcp.mongodb.net/test?retryWrites=true&w=majority"
mongoose.connect(uri,{ useNewUrlParser: true, useCreateIndex: true ,useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open',() => {
console.log('Database connection established successfully');
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
//executes the files in the second argument when user enters the url 'rooturl/firstargument'
app.use('/exercises',exercisesRouter);
app.use('/users',usersRouter);
app.listen(port,() => {
console.log(`Server is running on port:${port}`);
});
In your heroku project you need to setup an env variable ATLAS_URI and enter the value for your mongodb uri.
To do so go to the settings tab in your heroku app, then click on reveal config vars, and then enter the key and value for your mongo uri.
Hope this helps

How to trigger a service in App Engine on Firebase data change

I have created an app engine basic server and connected it for Firebase:
// server.js
// Express packages
const express = require('express');
const app = express();
const path = require(`path`);
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
// Firebase packages
var firebase = require('firebase');
var firebaseConfig = {...};
var fire = firebase.initializeApp(firebaseConfig);
var ref = firebase.database().ref('test');
ref.on('child_added', readMessage);
function readMessage(data) {
console.log('data', data)
};
// Route index
app.get('/', (req, res) => {
res.send('Hello from App Engine!');
});
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
My idea was to trigger this service (not sure which route, but I guess it is open?) when a child is added to the node test on Firebase.
To give a bit of background information, I am basically planning to create a peer connection using webrtc and then parse the video on this nodejs server. I use Firebase for signallin by sending the webrtc information to the node test and then the server can read and process this once there is a change.
I do not understand however how to trigger this service when a child is added (thus when I send some meta data to the node test in Firebase). How do I structure my nodejs code to handle this? Or should this be done differently?
Using cloud function with Firebase Realtime Database triggers, we can call the app engine endpoint using http or Cloud Tasks.

Issue with a 404 error using socket.io

I've recently gotten into socket.io, during a long-term project of mine. Which is probably why I am having such a hard time of it, because their "getting started" sections don't take into account you may already be deep into development of your own application. The main issue is it connecting, it won't do it, client-side that is.
I keep getting a 404 not found which is cause by CANNOT POST /socket.io/ Which it is right, it can't obviously, mainly because that is not where the socket.io location is (it is in node_modules per usual). Secondly if I create a route for this, it does absolutely nothing. So here is code initializing it:
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const db = require('./config/db');
// Init App
const app = express();
// Init http server
const server = http.createServer(app);
// init socket
const io = require('socket.io').listen(server);
Here is the clientside trying to connect to it:
if (window.location.hostname == 'playkog.net' || window.location.hostname == 'www.playkog.net') {
var port = 443;
} else {
var port = 8080;
}
var connected = false;
var socket = io.connect(window.location.hostname + ':' + port, { 'connect timeout': 5000 });
// Connection Successful
socket.on('connect', function () {
console.log('a user connected');
connected = true;
});
socket.on('disconnect', function () {
console.log('user disconnected');
connected = false;
});
I imagine I'll have to connect to a different port, however I'm not sure which, nor if that is my issue (or only issue). Of course be extremely new to this kind of stuff (amateur at best) some of these things just go right over my head.
Here is a screenshot of my console

"Cannot get /" in Swagger, Express and Node.js

I am working with Swagger, Express and Node to define and run endpoints. A GET request on the localhost/docs returns all the relevant routes. But when I try a GET request on any of the routes, it returns a "Cannot Get /XXX"
Index.js
'use strict';
var fs = require('fs'),
path = require('path'),
// Basic Setup new express
http = require('http'),
express = require('express'),
mysql = require('mysql'),
parser = require('body-parser');
var swaggerTools = require('swagger-tools');
var jsyaml = require('js-yaml');
// Setup express
var app = express();
app.use(parser.json());
app.use(parser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 5000);
// Database Connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'sample_database'
});
try {
connection.connect();
console.log('Database connected!');
} catch(e) {
console.log('Database Connetion failed:' + e);
}
// swaggerRouter configuration
var options = {
swaggerUi: path.join(__dirname, '/swagger.json'),
controllers: path.join(__dirname, './controllers'),
useStubs: process.env.NODE_ENV === 'development' // Conditionally turn on stubs (mock mode)
};
// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
var spec = fs.readFileSync(path.join(__dirname,'api/swagger.yaml'), 'utf8');
var swaggerDoc = jsyaml.safeLoad(spec);
// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
app.use(middleware.swaggerMetadata());
// Validate Swagger requests
app.use(middleware.swaggerValidator());
// Route validated requests to appropriate controller
app.use(middleware.swaggerRouter(options));
// Serve the Swagger documents and Swagger UI
app.use(middleware.swaggerUi());
// Create server
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
});
While initialising the middleware, I tried using:
app.use(express.static(__dirname + './controllers'));
But the error is still present. I think this has got something to do with the routing but I am not sure where is the error is.
The directory structure for the code is:
-my_app
|
+--controllers
| |
| +--user.js
| +--userService.js
+--index.js
Try use this construction
require('./controllers/<your_routing_file>')(app);
and type routes not in index.js

Resources