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.
Related
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".
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);
}
}
I'm trying to store emails from sendgrid via the inbound webhook using node, express and multer. There is an example on sendgrids site as below:
var express = require('express');
var multer = require('multer');
var upload = multer();
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(multer());
});
app.post('/parse', upload.array('files', 3) function (req, res) {
var from = req.body.from;
var text = req.body.text;
var subject = req.body.subject;
var num_attachments = req.body.attachments;
for (i = 1; i <= num_attachments; i++){
var attachment = req.files['attachment' + i];
// attachment will be a File object
}
});
var server = app.listen(app.get('port'), function() {
console.log('Listening on port %d', server.address().port);
});
This code throws an error when an email with an attachment is sent. The error is "unexpected field". I assume that the declaration for array.upload("files",3) is where the issue lies. Has anybody solved this?
You can solve this by using .any() when you don't the field name (see documentation for any()
Here's an example code
app.post('/parse', upload.any() function (req, res) {
var from = req.body.from;
var text = req.body.text;
var subject = req.body.subject;
var num_attachments = req.body.attachments;
for (i = 1; i <= num_attachments; i++){
var attachment = req.files['attachment' + i];
// attachment will be a File object
}
});
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);
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/