connect mongo to node error - javascript

Im tring to connect node server to mongo and there is my code :
var http = require("http");
var url = require("url");
var Router = require('node-simple-router');
var router = Router();
var qs = require('querystring');
var mongoose = require('mongoose');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// mongo connection and use
mongoose.connect('mongodb://localhost/jobs');
var db = mongoose.connection;
db.on('error', function() {console.log("error")});
db.once('open', function () {
console.log("connected!");
// init the schema
var jobSchema = mongoose.Schema({ bName: String , phone :Number ,location:[{longitude:Number,latitude:Number}],Email:String,field:String,exp:String});
jobSchema.methods.printDetails = function() {
var str = "id=" + this.id + " name="+this.name;
console.log(str);
};
var job = mongoose.model('jobs',jobSchema);
//adding a jobs for testing :
var testJob = new job ({bName: 'Microsoft' , phone :'035588319' ,location:[{longitude:'7.8',latitude:'7.8'}],Email:'microsoft#gmail.com' ,field:'QA',exp:'0-2'});
testJob.save(function(error,prod) {
if(error) {
console.log(error);
}
else {
console.log("a job was saved to mongodb");
//testJob.printDetails();
}
)};
function start(route) {
function onRequest(request, response) {
var path = url.parse(request.url).pathname;
console.log("Request for " +path+ "received.");
route(path);
if(request.method==='GET')
{
response.writeHead(200, {"Content-Type": "text/plain","access-control-allow-origin":"*"});
console.log(request.body);
response.end("res");
}
else if(request.method === 'POST')
{
response.writeHead(200, {"Content-Type": "text/plain","access-control-allow-origin":"*"});
//var userString = JSON.stringify(body);
response.end("POST REQUEST");
}
else if (request.method==='PUT')
{
response.writeHead(200, {"Content-Type": "text/plain","access-control-allow-origin":"*"});
response.end("put request");
}
else if(request.method==='DELETE')
{
response.writeHead(200, {"Content-Type": "text/plain","access-control-allow-origin":"*"});
response.end("delete request");
}
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
i dont start my server because of syntax error on line 79 , but i only have 78 lines .
syntax error unexpected end of input : }); , and can anyone tell me if this is the right way to connect between the mongo and the node web server .

When you call db.once("open", function () { you never close that paren and brace.
I think you want a }); after the testJob declaration. That should also be }) and not )}.

Related

socket io how to emit event to buddies?

Hi I'm making a chat with node js and I have a question. The chat is global, without rooms but users can only see and write to users in their buddy list. So when they connect to the server, they'll send also the user id and the buddy list as array. In the server I have a global variable with online users. Now, which is the best way to emit the event to users in the buddy list?
This is my current code:
var express = require('express');
var cors = require('cors');
var crypto = require('crypto');
var app = express();
var port = process.env.PORT;
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var socketio = require('socket.io');
var confdb = require('./lib/config-db.js');
var conf = require('./lib/config.js');
var db = require('./lib/chat-db');
var whitelist = [];
var secret_st = '';
var chrlimit = '';
var socketio_jwt = require('socketio-jwt');
var uidlist = {};
var id = {};
var mongodburl = process.env.MONGODB_URI;
// initialize db ===============================================================
mongoose.connect(mongodburl); // connect to our database
mongoose.Promise = global.Promise;
// set up our express application
confdb.findOne({'check': '1'}).exec(function(err, docs){
if (docs) {
whitelist = docs.origin;
secret_st = docs.spku;
chrlimit = docs.chrlimit;
if (docs.badwld) {
badwl = JSON.parse(docs.badwld);
}
} else {
conf.saveconfig();
}
startall();
});
function startall() {
var corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
};
app.use(cors(corsOptions), function(req, res, next) {
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// launch ======================================================================
var server = app.listen(port);
var io = socketio.listen(server);
//Routes ======================================================
app.get('/', function(req, res) {
res.writeHead(200);
res.end();
});
var nspm = io.of('/member');
nspm.use(socketio_jwt.authorize({
secret: secret_st,
handshake: true
}));
nspm.on('connection', function(socket) {
db.c_oneusr(socket.decoded_token, function(err, docs){
nspm.to(socket.id).emit('ckusr', 'ok');
initializeConnection(socket, 0);
});
});
function initializeConnection(socket, lstshout){
showActiveUsers(socket, lstshout);
}
function showActiveUsers(socket, lstshout){
socket.uid = socket.decoded_token.uid;
uidlist[socket.uid] = 1;
if (!id[socket.uid]) {
id[socket.uid] = {};
}
if (!msgtime[socket.uid]) {
msgtime[socket.uid] = [];
}
msgtime[socket.uid]['lpmsgt'] = lstshout;
id[socket.uid][socket.id] = 1;
socket.emit('login', {
uidlist: uidlist
});
// I need to change this and emit it only to buddies
socket.broadcast.emit('user joined', {
uidlist: uidlist,
uid: socket.uid
});
data = [];
data["uid"] = socket.decoded_token.uid;
data["id"] = socket.id;
data["buddies"] = socket.decoded_token.buddies;
db.updpml(data);
}
}

Can not read property '/' of undefined

I started studying node.js. I ask you questions while studying. when I run my code(server) and connect to localhost, It doesn't work properly.
This is error:
This is my code:
index.js
var server = require('./server');
var router = require('./router');
var requestHandlers = require('./requestHandlers');
var handle = {};
handle['/'] = requestHandlers.view;
handle['/view'] = requestHandlers.view;
handle['/create'] = requestHandlers.create;
server.start(router.route, requestHandlers.handle);
server.js
var http = require('http');
var url = require('url');
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log('\nrequest for ' + pathname + ' received.');
response.writeHead(200, {'Content-Type' : 'text/plain'});
// route(handle, pathname); // injected function call
var content = route(handle, pathname);
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8000);
console.log('server has started.');
}
exports.start = start;
router.js
function route(handle, pathname) {
console.log('about to route a request for ' + pathname);
if (typeof handle[pathname] === 'function') {
return handle[pathname]();
} else {
console.log('no request handler found for ' + pathname);
return "404 Not found";
}
}
exports.route = route;
requestHandlers.js
function view(response) {
console.log('request handler called --> view');
return "Hello View";
}
function create(response) {
console.log('request handler called --> create');
return "Hello Create";
}
exports.view = view;
exports.create = create;
In index.js, you're passing requestHandlers.handle, which doesn't exist, rather than the handle object that you've created.
var server = require('./server');
var router = require('./router');
var requestHandlers = require('./requestHandlers');
var handle = {};
handle['/'] = requestHandlers.view;
handle['/view'] = requestHandlers.view;
handle['/create'] = requestHandlers.create;
// server.start(router.route, requestHandlers.handle);
server.start(router.route, handle);

S3 connection to application

I wrote an app that displays images by ID and all the images save and located in S3.
I have 2 instances and 1 LB in my AWS machine and the index.js is located in both instances.
In my index.js I wrote the path to my S3 bucket and I get an error message like this :
Blockquote
This XML file does not appear to have any style information associated with it. The document tree is shown below.
The code in index.js :
//Get Images Names by Id / Color from MongoDB
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://db_usr:db_pass#ds023550.mlab.com:23550/db_ringapp2016_g');
var userSchema = require('./1_define_schema');
var size = 0;
var express = require('express'),
url = require('url'),
app = express();
var fs = require('fs');
var http = require('http');
var Upload = require('s3-uploader');
var restify = require('restify');
app.listen(process.env.PORT || 3000);
// connection error
mongoose.connection.once('error', function (err) {
console.log('connectiob error' + err);
});
//connecting to DB
mongoose.connection.once('open', function () {
console.log("============================");
console.log("Connected Successfully to DB");
console.log("============================");
userSchema.find({}, function(err, user){
if(err) throw err;
//first route - call first get function from WS.
app.get('/AllPictures' ,
function (req, res) {
console.log("DB: Get all Pictures");
res.status(200).json(user[0].Name);
});
})
//second route - call second function from WS (by Id).
app.get('/PicById/:Id/:Size', function (req, res) {
userSchema.find({Id:req.params.Id} , function(err, user){
if(err) throw err;
console.log("DB: Get Pic by ID: "+req.params.Id+" from MongoDB");
console.log("Name Pic: "+user[0].Name);
console.log("Size Pic: "+req.params.Size);
var temp = user[0].Name.split(".");
var result = temp[0]+req.params.Size+"."+temp[1];
console.log(result);
res.send('<!DOCTYPE HTML><html><head></head><body><img src="https://s3-us-west-2.amazonaws.com/galshaharbucket/'+result+'"></body></html>');
console.log("============================");
})
})
//thired route - call thired get from WS (by Color).
app.get('/PicByColor/:Color', function (req, res) {
userSchema.find({Color:req.params.Color}, function(err, user){
if(err) throw err;
var names = [];
console.log("DB: Get Pic by Color: "+req.params.Color+" from MongoDB");
console.log("--------------------");
for(var i = 0; i<user.length; ++i){
var temp = user[i].Name.split(".");
names [i] = temp[0]+"S."+temp[1];
console.log("Name Pic: "+names [i]);
console.log("--------------------");
}
var temp = [];
for(var i = 0; i<user.length; ++i){
temp [i] = '<img src="https://s3-us-west-2.amazonaws.com/galshaharbucket/'+names [i]+'">'
}
var result = temp.join("");
res.send('<!DOCTYPE HTML><html><head></head><body>'+result+'</body></html>');
console.log("============================");
})
})
app.get('/GetAllPictures', function (req, res) {
userSchema.find({}, function(err, user){
if(err) throw err;
var names = [];
console.log("DB: Get All Pictures from MongoDB");
for(var i = 0; i<user.length; ++i){
var temp = user[i].Name.split(".");
names [i] = temp[0]+"S."+temp[1];
}
var temp = [];
for(var i = 0; i<user.length; ++i){
temp [i] = '<img src="https://s3-us-west-2.amazonaws.com/galshaharbucket/'+names [i]+'">'
}
var result = temp.join("");
res.send('<!DOCTYPE HTML><html><head></head><body>'+result+'</body></html>');
console.log("============================");
})
})
// Upload an image
app.get('/Upload/:Path', function (req, res) {
var knox = require('knox').createClient({
key: 'AKIAJ4ROKKJBECGFSYIA'
, secret: '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'
, bucket: 'galshaharbucket'
});
var file = req.params.Path;
console.log(file);
var upload_name = "upload_"+ file; // or whatever you want it to be called
knox.putFile(file, upload_name, {
"Content-Type": "image/jpeg"
}, function (err, result) {
if (err != null) {
return console.log(err);
} else {
console.log("Uploaded to amazon S3");
console.log("--------------------");
}
});
})
});
// The function that recieve the name from mongo and display it
function getImageById(){
Input = document.getElementById("imageId");
Size = document.getElementById("imageSize");
size=Size.value;
alert(size);
if(Input.value==""){
alert("Please Enter Id Number Between 1-33");
return;
}
url = "https://s3-us-west-2.amazonaws.com/galshaharbucket/PicById/"+Input.value+"/"+Size.value;
//url = 'https://s3-us-west-2.amazonaws.com/galshaharbucket/'+name;
if(Size.value=="L"){
popupWindow = window.open(
url,'popUpWindow','height=658,width=1120,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
if(Size.value=="M"){
popupWindow = window.open(
url,'popUpWindow','height=525,width=820,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
if(Size.value=="S"){
popupWindow = window.open(
url,'popUpWindow','height=330,width=520,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
}
function getImageByColor(str){
Input = document.getElementById("imageColor");
if(Input.value==""){
alert("Please Enter a Color: red / green / blue / yellow");
return;
}
else{
path = "https://s3-us-west-2.amazonaws.com/galshaharbucket/PicByColor/"+Input.value;
popupWindow = window.open(
path,'popUpWindow','height=608,width=1020,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
}
function uploadImage(){
var fileChooser = document.getElementById('path');
var results = document.getElementById('results');
var file = fileChooser.files[0];
alert(file.name);
path = "https://s3-us-west-2.amazonaws.com/galshaharbucket/Upload/"+file.name+"";
popupWindow = window.open(
path,'popUpWindow','height=608,width=1020,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
function getAllPics(){
path = "https://s3-us-west-2.amazonaws.com/galshaharbucket/GetAllPictures";
popupWindow = window.open(
path,'popUpWindow','height=608,width=1020,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
How I can display the image correctly without an error ? What can cause to this error ?
Thank you,
Tom
Edit your bucket policy and make sure to have something like (or use AWS policy generator under the Bucket Permission section).
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::galshaharbucket/*"
}
]
}
if galshaharbucket is your bucket name so it grants everyone access to the objects in the specified folder.
you can read more about bucket policies

NodeJS and SocketIO on Server

I have a problem with my NodeJS and SocketIO setup on my server,
I want to access the HTTP Port by doing
var socket = io.connect("http://domain.com:8070");
Sadly this returns ERR_CONNECTION_TIMED_OUT
Here is my Server:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app, { log: false })
, fs = require('fs');
var mysocket = 0;
var socket = 0;
app.listen(8070);
function handler (req, res) {
fs.readFile(__dirname + '/app/tpl/skins/habbo/client.php',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('Client successfully connected');
mysocket = socket;
});
//udp server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("Packet recieved from server: " + msg);
if (mysocket != 0) {
mysocket.emit('field', "" + msg);
mysocket.broadcast.emit('field', "" + msg);
}
});
server.on("listening", function () {
var address = server.address();
console.log("udp server listening " + address.address + ":" + address.port);
});
server.bind(41181);
and my Client:
<script src="http://domain.com:8070/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect(http://domain.com:8070);
socket.on("hello", function(l){
var k = l.split(/,/);
switch(k){
case "testing":
{
window.alert('lol');
return;
}
}
});
</script>
Any ideas on how I can get it to work on http://domain.com:8070? Thanks.
It looks like your socket is not listening on port 8070.
Untested, but worth a try :
var io = require('socket.io').listen(app.listen(8070), {log: false});
You can also remove the URL from your client (although it shoudn't change anything) :
var socket = io.connect();
Edit :
You should also wrap the address in quotes :
var socket = io.connect("http://domain.com:8070");

Nodejs setTimeout Database Issue

Here is my part of codes :
var nodePort = 3030;
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var db = require('mysql');
var dbPool = db.createPool({
host : 'localhost',
user : 'root',
password : '1234',
database : 'test',
port : 3306
});
var gcm = require('node-gcm');
var message = new gcm.Message();
var sender = new gcm.Sender('API'); //Api Key
var registrationIds = [];
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded() );
foo = function(){
dbPool.getConnection(function(objErr, objConn){
if(objErr){
console.log('ERROR');
}else{
objConn.query("SELECT * FROM person", function(Err, Rows, Fields){
for(var i=0; i<Rows.length; i++){
console.log(Rows[i].Name);
}
});
}
});
setTimeout(foo,1000);
}
foo();
app.listen(nodePort);
console.log('App listening on port' + nodePort);
This function runs only 10-time and stops, if i try to connect database .
I want to check my database every second, are there any ways to do it?
var nodePort = 3030;
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var db = require('mysql');
var dbPool = db.createPool({
host : 'localhost',
user : 'root',
password : '1234',
database : 'test',
port : 3306
});
var gcm = require('node-gcm');
var message = new gcm.Message();
var sender = new gcm.Sender('API'); //Api Key
var registrationIds = [];
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded() );
foo = function(){
dbPool.getConnection(function(objErr, objConn){
if(objErr){
console.log('ERROR');
}else{
objConn.query("SELECT * FROM person", function(Err, Rows, Fields){
for(var i=0; i<Rows.length; i++){
console.log(Rows[i].Name);
}
});
}
});
}
setInterval(function(){foo();},1000);
app.listen(nodePort);
console.log('App listening on port' + nodePort);

Categories