Can not get any page after running node server in Ubuntu - node.js

I uploaded all Node.js related file in Ubuntu server .i opened putty and typed my server's instance ip then started the server after moving to the uploaded file directory.The Node server is running successfully but when i tried to get the pages by typing the url e.g-*.*.*.*:8888 which contains the server's instance ip and port number no page is coming.It is throwing the message This webpage is not available ERR_CONNECTION_RESET.I am explaining my code and server's snap shot below.
server.js:
var port=8888;
var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var database='Oditek';
var collections=['video'];
var app= express();
var server=http.Server(app);
var io=require('socket.io')(server);
var db = mongo.connect("10.25.25.100:27017/"+database, collections);
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
app.use(methodOverride()); // simulate DELETE and PUT
db.on('ready', function () {
console.log('database connected')
});
app.get('/',function(req,res){
res.sendfile('view/login.html');
});
app.post('/login',function(req,res){
var username=req.body.username;
var password=req.body.userpassword;
if(username && password){
db.video.findOne({
username:username,
password:password
},function(err,doc){
if(doc){
console.log('login',doc);
res.send(doc);
}
if(err){
console.log('login12',err);
res.send("could not login");
}
});
}
});
app.get('/index',function(req,res){
res.sendfile('view/index.html');
});
app.get('/video',function(req,res){
res.sendfile('view/video.html');
});
app.get('/whiteboard',function(req,res){
res.sendfile('view/whiteboard.html');
});
//socket----programming//
var roomid;
var clients={};
io.on('connection',function(socket){
//console.log('socket id',socket);
if(socket.handshake.query.roomid){
roomid=socket.handshake.query.roomid;
}
var usertype=socket.handshake.query.usertype;
//var url=socket.handshake.headers.referer;
//var myString = url.substr(url.indexOf("?") + 1);
//var usertype=myString.substr(myString.indexOf("=")+1);
//console.log('usertype',usertype);
clients[usertype]={
"socket":socket.id
}
console.log('clients',clients['admin'].socket);
socket.on('admin-join',function(data){
if(data.IsJoinAdmin){
socket.join(roomid);
}
});
socket.on('user-join',function(data){
console.log('user wants to join',data);
//console.log('user type',clients);
if(data.isUserJoin){
io.sockets.connected[clients[data.usertype].socket].emit('user-already-joined',data);
socket.join(roomid);
}
});
socket.on('send-playing-video-request-to-users',function(data){
io.to(roomid).emit('sending-broadcasting',data);
});
socket.on('send-broadcasting-message',function(data){
io.to(roomid).emit('sending-broadcasting',data);
});
socket.on('share-white-board',function(msg){
io.to(roomid).emit('sharing-white-board',msg);
});
socket.on('disconnect', function() {
for(var user in clients) {
if(clients[user].socket === socket.id) {
delete clients[user];
io.to(roomid).emit('user-has-left',{userleft:true});
break;
}
}
})
});
server.listen(port);
console.log('server is listening on the port'+port);
Here i can not get the pages even if the server is running.Please help me to get the pages after running the node server.

Related

Sample Hello World Express App is returning binary data

The following doesnt seem to work. It's simple Express sample code. You can ignore the other responses. Im just trying to get the basic '/' home page working and that's refusing to work. Code is as follows:
var express = require('express');
var sR = require('./routes/index');
var path = require('path');
var urlencoded = require('url');
var bodyParser = require('body-parser');
var json = require('json');
var methodOverride = require('method-override');
var jade = require('jade');
var fs = require('fs');
var http = require('http2');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const dbLoc = 'mongodb://localhost:27017';
const dbName = 'gothamDB';
var dbConn = null;
const dbURL = "mongodb://gotthamUser:abcd1234#localhost:27017/gothamDB"
const mongoClient = new MongoClient(dbURL, { useNewUrlParser: true, useUnifiedTopology: true});
// Use connect method to connect to the server
dbConn = mongoClient.connect(function(err, client) {
assert.strictEqual(null, err);
console.log("Connected successfully to server");
dbConn = client;
});
var app = express();
app.set('port', 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', jade);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.set('/', function(req, res){
res.send("Hello World");
res.end();
console.log("Hello World sent");
});
app.post('/create_collection', function(req, res){
var db = dbConn.db('gothamDB');
var userData = db.createCollection(req.body.coll_name, function(err){
if(err){
res.send('Error creating database: ' + req.body.coll_name);
return;
}
res.send('Database ' + req.body.dbname + ' created successfully');
});
});
app.post('/new_contact', function(req, res){
var name = req.body.name;
var phone = req.body.phone;
var db = dbConn.db('gothamDB');
var coll = db.collection(req.body.coll_name);
collection.insert(
{name : name, phone: phone}
, function(err, result) {
assert.strictEqual(err, null);
assert.strictEqual(1, result.result.n);
assert.strictEqual(1, result.ops.length);
res.send("Inserted new record into the collection");
});
});
app.post('view_contact', function(req, res){
var db = dbConn.db('gothamDB');
var coll = db.collection(req.body.coll_name);
coll.find({'phone' : req.body.phone}).toArray(function(err, docs){
if(err) {
res.send("Error looking up the data");
return;
}
res.send(docs);
return;
});
});
app.post('delete_contact', function(req, res){
var db = dbConn.db('gothamDB');
var coll = db.collection(req.body.coll_name);
coll.deleteOne({'phone' : req.body.phone}).toArray(function(err, docs){
if(err) {
res.send("Error looking up the data");
return;
}
res.send(docs);
return;
});
});
//const key = path.join(__dirname + '/security/server.key');
//const cert = path.join(__dirname + '/security/server.crt');
const options = {
key: fs.readFileSync(__dirname + '/security/server.key'),
cert: fs.readFileSync(__dirname + '/security/server.crt')
}
http.createServer(app).listen(app.get('port'), function(err){
console.log('Express server lisetning on port ' + app.get('port'));
})
console.log("Server started");
Any clue? Browser shows as follows:
Itt's showing an ERR_INVALID_HTTP_RESPONSE
if I run a curl command, it shows the following:
NodeExample % curl -X GET 'http://localhost:8080/'
Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file
If I put a breakpoint at the line:
res.send("Hello World");
that never hits. I've also tried putting in
res.header("Content-Type", "application/json");
but since the breakpoint never hits, it is not going to help I guess.
You are using set here
app.set('/', function(req, res){
res.send("Hello World");
res.end();
console.log("Hello World sent");
});
It should be get
app.get('/', function(req, res){
res.send("Hello World");
res.end();
console.log("Hello World sent");
});

How to setup socket.io for getting data real-time

I'm new to mean-stack and I followed some instruction on how to get real-time data. I tried every single steps but none of it is working, how can I use socket.io correctly? I provided my code here for getting users from mongodb, please do correct my code
server.js
var express = require ('express');
var app = express();
var server = require('http').Server(app);
var http = require('http').Server(app);
var io = require('socket.io')(http);
var morgan = require ('morgan');
var mongoose = require('mongoose');
var appRoutes = require('./app/routes/api');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.use('/api',appRoutes);
mongoose.connect('mongodb://localhost:27017/testing', function(err){
if(err){
console.log('Not connected' + err);
} else
{
console.log('Connected');
}
});
Then here is the part where I get the users from the table, I don't know how to get the the data real-time:
api.js
var User = require('../models/user');
const router = express.Router();
router.get('/management', function(req, res) {
User.find({}, function(err, users) {
if (!users) {
res.json({ success: false, message: 'Users not found' });
} else {
res.json({ success: true, users: users,});
}
});
});
userCtrl.js
.controller('managementCtrl', function(User, $scope) {
function getUsers() {
User.getUsers().then(function(data) {
if (data.data.success) {
app.users = data.data.users;
} else {
app.errorMsg = data.data.message;
}
});
}
});
userServices.js
angular.module('userServices', [])
.factory('User', function($http) {
var userFactory = {};
userFactory.getUsers = function() {
return $http.get('/api/management/');
};
return userFactory;
});
};
users.html
<tbody>
<tr ng-repeat="person in management.users">
<td align="center">{{ person.name }}</td>
<td align="center">{{ person.email }}</td>
</tr>
</tbody>
You have to make establish persistent socket connection with the frontEnd. After making the persistent connection you have to listen for the particular event and then send the realtime user Data.
You can achieve this by:
server.js
var express = require ('express');
var app = express();
var server = require('http').Server(app);
var http = require('http').Server(app);
var io = require('socket.io')(http);
var morgan = require ('morgan');
var mongoose = require('mongoose');
var appRoutes = require('./app/routes/api');
var User = require('../models/user');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.use('/api',appRoutes);
mongoose.connect('mongodb://localhost:27017/testing', function(err){
if(err){
console.log('Not connected' + err);
} else
{
console.log('Connected');
}
});
io.on('connection', function(socket) {
console.log('New Socket has been connected');
socket.on('getUserDetails', function() {
User.find({}).then(function(data){
socket.emit('userDetails', data)
})
})
})
In fronEnd you can emit the event getUserDetails for getting the data from the server and listen on userDetails for getting the response from the server.
Something like this can be implemented in front end
angular

How to send message to frontend in case of MongoDb connection Failed

Is there any way to send error to frontend on mongoDb connection error.I had tried in a different different way but I didnt get a solution.
var express = require('express');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
app.get('/',function(req,res){
res.send('NOT Connected....')
});
});
You can use web sockets to push this information to the UI.
const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);
const io = require('../..')(server);
const port = process.env.PORT || 3000;
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
socket.emit('mongodb-failed', error)
});
});
server.listen(port, () => {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
// when socket emits 'mongodb-connection-failed', this listens and executes
socket.on('mongodb-failed', (data) => {
// we tell the client to execute 'new message'
socket.broadcast.emit('mongodb-connection-failed', {
errorDetails: data
});
});
});
now at client side:
var socket = io();
socket.on('mongodb-connection-failed', () => {
console.log('you have been disconnected');
//do more whatever you want to.
});
This above example is using socket.io.
You can use any web socket library, see more here

NodeJS procedure execution flow

I am new to Nodejs and aslo coming from a procedural language background so I have this need to know the execution flow of my code. I have a general question about the flow of Nodejs procedures. This is the scenario:
The code structure:
Appnamefolder
...standard node folders(.idea,css,fonts,etc)
...model
....database.js (connect to db and execute db queries)
...public
...routes
....users.js (GET and POST procedures....calls db queries via module.export)
...views
...app.js
...other js files
The question concerns the database. Since the DB connect is not in the app.js file but in a .js file in the model folder at what point is the DB connection made? and is a connection made every time a DB query is made?
What I hope to happen is that the DB connect is made one time and remain connected until the app is terminated. I tried putting the DB connect in app.js but I get an error when I attempt a DB query so I have to place the DB connect in the same file as the DB queries......Somehow this seems wrong to me. Can anyone explain how node handle this flow?....will be appreciative of any assistance.
EDIT: HERE IS A SAMPLE OF THE CODE
app.js
var express = require('express');
var path=require('path');
var bodyParser = require('body-parser');
var cookieParser=require('cookie-parser');
var expressSession=require('express-session');
var expejs = require('ejs');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var expressSession = require('express-session');
var expressLayouts=require("express-ejs-layouts") // add this requirement
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var crypto = require("crypto");
var loaddealerTable=require('./loaddealerTable');
//var neo4j = require('neo4j-driver').v1;
// var neo4jdb = neo4j.driver("bolt://localhost:7474", neo4j.auth.basic("neo4j", "password"),
// {
// trust: "TRUST_ON_FIRST_USE",
// encrypted:true
// });
//***************Notifications Permission*******
var routes = require('./routes/index');
var users = require('./routes/users');
var csocket=require('./socketconnections');
var app=express();
var server=require('http').createServer(app);
sockets = require('./socketserver');
//rpaMessageWaiting = require('./getRPAmessages');
//var io=require('socket.io').listen(server);
// View Engine
app.set('views', path.join(__dirname,'views'));
app.set('view options', { layout:'layout.ejs' });
app.set('view engine','ejs');
//bodyParsers middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(expressLayouts);
//set up public folder
app.use(express.static(path.join(__dirname, '/public')));
// set express session with secret
app.use(expressSession({ secret: process.env.SESSION_SECRET || 'secret',
resave: true,
saveUninitialized: true
}));
// Passport initialization
app.use(passport.initialize());
app.use(passport.session());
//Express Validitor...validate inputs..taken from github middleware options
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// connect flash middleware
app.use(flash());
// set global variables for flash messages
app.use(function (req, res, next)
{
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
// Middelware for route files
app.use('/', routes);
app.use('/users', users); //need to check routing
sockets.startSocketServer(server);
//load dealer table
console.log("load dealer table");
**loaddealerTable(); //First call on the DB**
//============socket io listening=======================
app.set('port',(process.env.PORT|| 3000));
server.listen(app.get('port'), function()
{
console.log('Server started on port '+app.get('port'));
// console.log('Server started on port .....');
// app.get('/index',function (req,res) {
// // body...
// res.render(__dirname+'/index');
});
loaddealertable.js
var loaddealerTable=function()
{
var memorytbl=require('./memorytables');
var User = require('./model/user');
var getHashKey=require('./gethashkey');
const hashMax=1000;
console.log("call get dealers from DB");
User.getallDealers(function(err,dealerFound,result)
{
if (dealerFound)
{
//
for (i=0; i< result.records.length; i++)
{
memorytbl.Dealer.email =result.records[i].get(0).properties.email;
memorytbl.Dealer.name =result.records[i].get(0).properties.name;
memorytbl.Dealer.telephone =result.records[i].get(0).properties.storenumber;
memorytbl.Dealer.creditcard =result.records[i].get(0).properties.creditcard;
memorytbl.Dealer.delivery =result.records[i].get(0).properties.delivery;
memorytbl.Dealer.location =result.records[i].get(0).properties.location;
memorytbl.Dealer.rating =result.records[i].get(0).properties.rating;
var hashIndex = getHashKey(memorytbl.Dealer.email ,hashMax);
memorytbl.DealersQ[hashIndex]=memorytbl.Dealer;
} //end of for i
} //end of if....
else
{
console.log("No dealers found....table is empty");
}
}) //end of loaddealers table db call
} //end of load dealers table function
module.exports=loaddealerTable;
user.js
var express = require('express');
var bcrypt = require('bcryptjs');
var router = express.Router();
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "password"));
var session = driver.session();
//============Load Memory Tables=========================
router.getallDealers=function(callback) {
session
.run ("MATCH (user:Dealer) RETURN user")
.then (function(result)
{
if ( !result.records[0])
{
console.log("No Dealers Found");
session.close();
if (typeof callback==="function") {
return callback(null,false,result);
}
} // end of if not found
else
{
console.log("Dealer Found");
session.close();
if (typeof callback === "function")
{
return callback(null, true, result);
}
}
// or close session here??
}) //end of .then block
.catch(function(err)
{
console.log("DB call error: "+err);
}); //.then block
} //end of get dealers
For a start you have to understand that each file is a module.
Your app starts with running a single js file (module) like node app.js.
One module can load another module and another and so on.
Your folder structure does not have any effect on the order by itself. It all depends on your code and in what order do you load modules. While your sync code will run in the order you write it your async code will run in the future and you need to understand the event loop to understand what happens in your code.
From the small context you gave I guess you might tried to query your database before you connected to it. I don't see your code but it can happen regardless of where you connect (app.js file or another).

Error while posting data from one server to another server running on different ports

I am writing a program which will send a mail on clicking a button in html using nodemailer.
My Application server is running on 8383 port and the node server is running on 8080.
I am getting an error "POST http://127.0.0.1:8080/Webcontent/api/mail 404 (Not Found) 127.0.0.1:8080/Webcontent/api/mail:1
Error: Cannot POST /Webcontent/api/mail"
Kindly look into the code and suggest a solution.
server.js file
var express = require('express'),
cors = require('cors');
var app = express();
app.use(cors());
var port = process.env.PORT || 8080;
var database = require('./config/database');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
app.use(express.static(__dirname + '/public'));
app.use(morgan());
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride('X-HTTP-Method-Override'));
require('./app/routes.js')(app);
app.listen(port);
console.log("App listening on port " + port);
routes.js file
var User = require('./models/user');
var Mail = require('./models/mail');
module.exports = function(app) {
app.post('http://127.0.0.1:8080/Webcontent/api/mail ', function(req, res) {
console.log('inside post');
Mail.fire(req.body.text1);
console.log(req.body.text1);
});
app.get('*', function(req, res) {
console.log('fff');
res.sendFile('index.html', { root: path.join(__dirname, './public') });
});
};
mail.js file
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail", // sets automatically host, port and connection security settings
auth: {
user: "test#gmail.com",
pass: "Test"
}
});
exports.fire= function fire(username){
smtpTransport.sendMail({ //email options
from: "test#gmail.com", // sender address. Must be the same as authenticated user if using GMail.
to: "receive#yahoo.com", // receiver
subject: "mail using nodemailer", // subject
text: "mail body text" // body
}, function(error, response){ //callback
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
smtpTransport.close(); // shut down the connection pool, no more messages. Comment this line out to continue sending emails.
});
};
controller.js file// used to call the function(sendmail) on button click
$scope.sendMail = function() {
//alert("inside createtodo");
$http.post('http://127.0.0.1:8080/Webcontent/api/mail', $scope.formData).success(function(data) {
//alert("inside success");
$scope.formData = {};
$scope.users = data;
//console.log(data);
})
.error(function(data) {
//alert("Bad Luck....");
console.log('Error: ' + data);
});
};
Just change in your route.js file:
app.post('/Webcontent/api/mail', function(req, res) {
console.log('inside post');
Mail.fire(req.body.text1);
console.log(req.body.text1);
});

Resources