Nodejs setTimeout Database Issue - javascript

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);

Related

JavaScript for loop for object

I'm using Express to 'capture' data. I'm using a put request. My request is
localhost:3000/units/10 , with the body being:
{
"relayon0" : 400,
"relayoff0" : 400
}
And my code is:
var bodyParser = require('body-parser');
var mysql = require('mysql');
var express = require('express');
var app = express();
var conn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'plc'
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.put('/units/:id', function(req,res){
var id = req.params.id;
var relayon = [];
var relayoff = [];
for(var i = 0; i < 8; i++){
relayon[i] = JSON.stringify(req.body.relayon + i);
relay[i] = JSON.stringify(req.body.relayoff + i);
}
res.send(relayon[0]);
});
app.listen(3000);
The response returns null.
Any ideas on what the issue is?
What you probably want is req.body['relayon' + i] and req.body['relayoff' + i].
Requesting req.body.relayon + i results in value of req.body.relayon (which is undefined) being added with number, which results with NaN. Being stringified, it results with "null".

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);
}
}

express session Cannot set property 'id' of undefined

var redis = require('redis');
var router = express.Router();
var mysql = require('mysql');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var client = redis.createClient();
var session = require('express-session'),
RedisStore = require('connect-redis')(session);
var app = express();
app.use(cookieParser);
app.use(session({
store : new RedisStore({
host:'localhost',
port:7351,
maxAge: 300000,
client:client,
ttl:260
}
),
secret:'dafdsa',
resave:false,
saveUninitialized:true,
}));
this is my setting and this is my code
router.post('/', function(req, res, next) {
var id = req.body.userid;
var passwd = req.body.password;
var sess = req.session;
var login_chk = pool.getConnection(function(err,connection){
connection.query('SELECT U_passwd FROM Member WHERE U_id = ?',[id],function(err,row,req){
if(err)console.log(err);
var sqlpasswd = row[0].U_passwd;
var answer = 0;
answer = passwd_chk(passwd,sqlpasswd);
if(answer ===1){
save_session(id);
res.render('main');
}
var save_session = function(req){
req.session.id = req;
}
i will post (login) and i save id in session but this code is always err to cannot set property... how can i fix it?...
thanks for answer
This happens cause you're passing userId as save_session(req) argument. Then you're doing req.session.id = req; in your case the same as userId.session.id = userId;. The error notices you that userId has not session property (Obsiously). All you need is pass req and userId as arguments. Change your code like this.
router.post('/', function(req, res, next) {
var id = req.body.userid;
var passwd = req.body.password;
var sess = req.session;
var login_chk = pool.getConnection(function(err,connection){
connection.query('SELECT U_passwd FROM Member WHERE U_id = ?',[id],function(err,row,req){
if(err)console.log(err);
var sqlpasswd = row[0].U_passwd;
var answer = 0;
answer = passwd_chk(passwd,sqlpasswd);
if(answer ===1){
save_session(req,id); <--- Change this
res.render('main');
}
var save_session = function(req,id){ <--- Change this
req.session.id = id; <--- Change this
}
I hope It helps.

connect mongo to node error

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 )}.

Why doesn't emit event fire by socket.io

I'm using socket.io + express.
I want to emit 'start' and 'user_info' event to server from client. But it doesn't work. I wrote like this...
server.js
var express = require("express");
var http = require("http");
var socket = require("socket.io");
var app = express();
var ejs = require("ejs");
var server = http.createServer(app);
var io = require("socket.io").listen(server);
var redis = require("redis");
var _ = require("underscore");
require("./models/User");
app.get("/",function(req,res){
res.render("index",{});
});
socket.on("start",function(data){
console.log("Started");
});
socket.on("user_info",function(user_info){
var self = this;
var name = user_info.name;
var password = user_info.password;
user.name = name;
user.password = password;
var data = JSON.stringify({name: name,password: password});
});
### client.js
$(document).ready(function(){
var socket = io.connect("http://localhost:8080");
$("#register-btn").on("click",function(data){
$("#notice").html("Registerd");
var name = $("#name").val();
var password = $("#password").val();
var confirmPassword = $("#confirm-password").val();
if (name && (password === confirmPassword)){
// user_info event is works.
socket.emit("user_info",{"name": name,"password": password});
// I wonder why start event does not works.
socket.emit("start",{"name": "yahoo"});
}else{
$("#notice").html("try again");
}
});
});
I don't know why 'start' event is not being fired. Do you have any idea?
You are missing the connection part of Socket.io
// Noticed I removed the var socket = require('....
var io = require("socket.io").listen(server);
io.sockets.on('connection', function (socket) {
console.log('Client Connected')
socket.on("start",function(data){
console.log("Started");
});
socket.on("user_info",function(user_info){
var self = this;
var name = user_info.name;
var password = user_info.password;
user.name = name;
user.password = password;
var data = JSON.stringify({name: name,password: password});
});
});
You may want to read the docs # http://socket.io/

Categories