I'm new to using mongo and having difficulties with set-up on local OSX server.
When I run node app.js my page appears on http://127.0.0.1:3000/ but I get this error:
Firefox can't establish a connection to the server at ws://127.0.0.1:3000/socket.io/?EIO=3&transport=websocket&sid=************. socket.io.js:5325:0
The connection to ws://127.0.0.1:3000/socket.io/?EIO=3&transport=websocket&sid=*************** was interrupted while the page was loading.
and when I refresh the page in firefox I get Unable to connect server at 127.0.0.1:3000. and the following error in terminal:
a user connected
/Users/******/express_intro/node_modules/mongodb/lib/url_parser.js:15
if(url.indexOf("mongodb://") != 0)
^
TypeError: Cannot read property 'indexOf' of undefined
at module.exports (/Users/******/express_intro/node_modules/mongodb /lib/url_parser.js:15:9)
at Function.MongoClient.connect (/Users/******/express_intro/node_modules/mongodb/lib/mongo_client.js:95:16)
at Namespace.<anonymous> (/Users/******/express_intro/app.js:48:8)
at Namespace.emit (events.js:107:17)
at Namespace.emit (/Users/******/express_intro/node_modules/socket.io/lib/namespace.js:205:10)
at /Users/******/express_intro/node_modules/socket.io/lib/namespace.js:172:14
at process._tickCallback (node.js:355:11)
Here is the app.js
var express= require('express');
var bodyParser=require('body-parser');
var path=require('path');
var app=express();
var mongo=require('mongodb').MongoClient;
var http = require('http'); //the variable doesn't necessarily have to be named http
//configure app
app.set('port',process.env.PORT || 3000);
app.set('view engine','jade');
app.set('views',path.join(__dirname,'views'));
//use middleware
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyParser.urlencoded({ extended: true }));
//define routes
var todoItems=[
{id:1,desc:'foo'},
{id:2,desc:'bar'},
{id:3,desc:'baz'}
];
app.get('/',function(req,res){
res.render('index',{
title:'My App',
items:todoItems
});
});
var serve=http.createServer(app);
var io=require('socket.io')(serve);
serve.listen(app.get('port'), function(){
console.log('Ready on port ' + app.get('port'));
});
io.on('connection',function(socket){
console.log('a user connected');
mongo.connect(process.env.CUSTOMCONNSTR_MONGOLAB_URI,function(err,db){
if(err){
console.warn(err.message);
}
else{
var collection=db.collection('chat messages')
var stream=collection.find().sort().limit(10).stream();
stream.on('data',function(chat){
console.log('emitting chat');
socket.emit('chat',chat.content);
});
}
});
});
Here is the client code
//var socket=io();
var socket = io('http://localhost:3000/');
$('#send-message-btn').click(function(){
var msg=$('#message-box').val();
socket.emit('chat',msg);
$('#messages').append($('<p>').text(msg));
$('#message-box').val('');
return false;
});
socket.on('chat',function(msg){
$('#message').append($('<p>').text(msg));
});
I also get this on loading the page first time
Any help appreciated.
Thanks
Related
i am unable to start my server.js file on Ubuntu server.I installed all npm packages successfully.But when i run command node server.js The script is not executing at all and there is no error also. After hit enter it is again move back to the folder path in putty ssh.I am explaining my code 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("127.0.0.1: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);
at least the console message should execute if this file is running.But i am not getting like that.Please help me to resolve this error.
There is another program called node which would show no output when called named "Amateur Packet Ratio Node program". From chatting with you, I have determined that this is what is on your system. There are two basic solutions.
Remove "Armature Packet Ratio Node program", and reinstall node.js
.
sudo apt-get purge node nodejs # Uninstall both
sudo apt-get install nodejs # Reinstall nodejs
Living with both programs and accessing node.js through node.js
.
nodejs server.js
forever -c 'nodejs server.js' start
I am using Cloude 9 environment for developing my nodejs app. In that I have written code to connect to mongodb database. I am successfully connecting to database and adding record to collection.
Now I want to send the collection info in return. But using res.send(collectionInfo); is not working.
Let me know how should I achieve this
Below is the code of my server.js file
var Db = require('mongodb').Db;
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var ejs = require('ejs');
var app = express();
var helpers = require('express-helpers')
var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var db;
helpers(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () {
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// MongoDB Connection
app.use(function(req, res, next) {
next();
})
app.get('/monogdb', function (req, res) {
res.render('monogdb.ejs');
});
app.post('/ajax-mongo-connect', function (req, res) {
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
if(err){
console.log(err);
}else{
var db = mongoClient.db("mydb");
db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } );
console.log('database connected',db);
var collectionInfo = db.collection("students");
mongoClient.close();
//res.setHeader('Content-Type', 'application/json');
res.send(collectionInfo);
}
})
})
As per #Roman Sachenko answer, I have tried to use
res.send(collectionInfo.toJSON()); but it is giving below error
/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299
throw err;
^
TypeError: Object #<Collection> has no method 'toJSON'
at /home/ubuntu/workspace/server.js:66:41
at MongoClient.open
(/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5)
at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11)
at process._tickCallback (node.js:442:13)
and using res.send({data: collectionInfo}); gives error
home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:299
throw err;
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at ServerResponse.res.json (/home/ubuntu/workspace/node_modules/express/lib/response.js:185:19)
at ServerResponse.res.send (/home/ubuntu/workspace/node_modules/express/lib/response.js:117:21)
at /home/ubuntu/workspace/server.js:67:21
at MongoClient.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/mongo_client.js:103:5)
at Db.open (/home/ubuntu/workspace/node_modules/mongodb/lib/mongodb/db.js:296:11)
at process._tickCallback (node.js:442:13)
Try to return this: res.status(200).json({'myCollection' : collectionInfo});.
You can find more details about express response here
Update:
After you explain the details, take a look at the code below:
app.post('/ajax-mongo-connect', function (req, res) {
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
if(err){
console.log(err);
res.status(500).json({message : 'OMG, an error occurred'});
}else{
var db = mongoClient.db("mydb");
db.createCollection("students", { name : req.body.nm, description : req.body.desc, location : req.body.loc } );
console.log('database connected',db);
var collectionInfo = db.collection("students");
// Here we will find all students
collectionInfo.find({}).toArray(function(err, students) {
// so now, we can return all students to the screen.
res.status(200).json({'myCollection' : students});
}
}
})
})
Cheers!
Mongoose ODM
First of all I would like to recommend you using Mongoose ODM:
https://github.com/Automattic/mongoose
So you will make you work with database much easier.
Basically it returns (Mongoose) normal object as results, but in case of issues you may try to use toObject() or toJSON() or as it mentioned create own object like {data: mongoCollection}
Examples:
res.send(collectionInfo.toObject());
res.send(collectionInfo.toJSON());
res.send({data: collectionInfo});
Please refer to the link in case of questions:
http://mongoosejs.com/docs/guide.html#toJSON
Native Driver
As for native driver, it also should return normally-constructed object, but according to issues I faced with in the past, JSON.stringify always helps if you set headers manually.
You may also check the contents of your entity. So you can just output it by console.log(collectionInfo);
Then just make sure that there is correct object inside.
And according to results you can take actions like:
res.send(JSON.stringify(collectionInfo)) //set headers manually
res.json(JSON.stringify(collectionInfo)) //you don't need to set headers
At least you will know what exactly is inside of collectionInfo. I think it will be enough to investigate the issue.
You can view circular JSON objects by doing this in node.js:
const util = require('util') // Native node module
util.inspect(circularObj)
You can call it from anywhere in the code, so it's very versatile.
I'm new to Socket.io and Express. I'm just working on getting the basic chat scenario up and running while assigning users to a session. From my research I've realized there are about as many ways to do this as there are stars. I've also realized that there really isnt one "accepted standard" (if I'm wrong, do show me). This was the simplest manner I figured out (using req.session.'name' = 'value')
Heres my server code:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, path = require('path')
, http = require('http')
, io = require('socket.io')
, cookie = require("cookie")
, connect = require("connect")
, app = express();
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'secret'}));
app.use(app.router);
});
var server = http.createServer(app);
server.listen(app.get('port'), function() {
console.log('ready');
});
var io = io.listen(server);
app.get('/', routes.index);
app.get('/user', routes.user);
io.sockets.on('connection', function (socket) {
socket.emit('connected', { connect: 'CONNECTED TO THE SERVER' });
socket.on('client connect', function (data) {
console.log("HEARD THE CLIENT");
});
socket.on('addingNewUser', function (data) {
console.log('BROADCASTING ADDUSER');
console.log(data);
socket.broadcast.emit('addUser', data);
});
});
Heres my index.jade code:
extends layout
block content
script(src="/socket.io/socket.io.js")
script(src="/javascripts/index.js")
script.
var socket = io.connect('http://localhost:3000');
socket.on('connected', function (data) {
socket.emit('client connect', { connect: 'CLIENT IS CONNECTED' });
});
socket.on('addUser', function (data) {
console.log("ADDING NEW USER:");
req.session.user = data;
console.log(data);
$("#usernames").append('<p>'+data+'</p>');
});
$(document).ready(function(){
$('#submit').click( function (data) {
console.log("SUBMITTING FORM!");
var userName = $("#add_user").val();
console.log("user name " + userName);
socket.emit('addingNewUser', { user: userName });
return false;
});
});
#users.large-3.columns
h5 Online Users
p#usernames
#messages.large-6.columns
form
fieldset
legend I am (the) Legend
input(type='text', id='add_user', name='add_user', placeholder='Type your name.')
input.button.small(type='submit', id="submit", value='Send')
#show_messages
ul#user_message
.large-3.columns
Some of the indentation might be off due to the StackOverflow formatting but in the actual file its good.
You can track all the console logs pretty well. It stops at the console.log after "BROADCASTING USER".
For some reason the listener for 'addUser' isnt picking up anything.
Any ideas?
Edit:
As pointed out in the comments, broadcast only emits to the sockets it did not originate from. So thats why it was never triggering the listener.
However, now I have a new problem. One that I've come across before.
In the listener for 'addUser' it returns an error for 'req.session.user' saying that 'Uncaught ReferenceError: req is not defined'.
How do I overcome this?
You are mixing up your client and server logic.
This code (from your template):
socket.on('addUser', function (data) {
console.log("ADDING NEW USER:");
req.session.user = data;
console.log(data);
$("#usernames").append('<p>'+data+'</p>');
});
Is executing on the client side where there is not req object available.
By default, socket.io and express sessions don't play together - you need to add some additional logic to your app.
There are several projects that aim to make this easier such as:
express.io
session.socket.io
I have a problem with Express.io: I try to create a chat but I am not able to use the Broadcast method.
No error message, but nothing happens.
app.js
var express = require('express.io')
, index = require('./routes/index.js')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
//configure options
});
app.http().io();
app.get('/', index.index);
app.io.route('ready', function(req) {
req.io.broadcast('newUser');
});
app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
user.js
io = io.connect();
io.emit('ready');
io.on('newUser', function(data) {
console.log("New user !!");
});
Error 2
WebSocket connection to 'ws://tchat.aws.af.cm/socket.io/1/websocket/n8Jm9Q7YYL8YdPRN4dxU' failed: Unexpected response code: 502
req.io.broadcast broadcasts to all connected clients except the client associated with the request. You should use app.io.broadcast to broadcast to all connected clients.
See the example given : https://github.com/techpines/express.io/tree/master/examples/broadcasting
I'm making a web-app that makes use of nodejs, mongodb, socket.io, express and mongoose.
I can start my server and correctly get the wanted html file in my browser when browsing to my localhost.
The problem I have is getting my socket.io to work.
On my server side everything works fine : I get " info - socket.io started " in my terminal.
But when surfing to my browser I get this in my browser console
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught ReferenceError: io is not defined
This is how i connect to socket.io.js
<script src="/socket.io/socket.io.js"></script>
and my map structure looks like this:
map
-app.js
-public
--index.html
-node_modules
--socket.io
--mongodb
--express
--jade
--mongoose
Does anyone knows what the mistake is I've made?
(it's actually the same problem as here: Node.js socket.io.js not found or io not defined )
Thanks in advance!
EDIT:
My code on the server side is this:
var app= require('express').createServer();
var io = require('socket.io').listen(app);
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/db');
app.listen(3030);
console.log("server started");
app.get('/',function(req,res){
res.sendfile(__dirname + '/public/index.html');
});
io.sockets.on('connection',function(socket){
console.log("connection made");
});
The first log, gets logged in the terminal ("server started"), but the second one ("connection made") doesn't get logged. So the connection isn't made.
I thought that was because of the wrong "set up" in my client side.
Check out the express migration guide 2->3
https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
Something like this should work
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/db');
server.listen(3030);
console.log("server started");
app.get('/',function(req,res){
res.sendfile(__dirname + '/public/index.html');
});
io.sockets.on('connection',function(socket){
console.log("connection made");
});
var app = express();
app.set('port', process.env.PORT || 3000);
...
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = socket.listen(server);
io.sockets.on('connection', function () {
console.log('hello world im a hot socket');
});