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".
Related
So , I have been try to display my variables "pares", "impares" ,"ninguno" in real time as the image below I used app.get and inside that a response.write to print de varibles, but the problem is if I want the varaibles to update, I need to reload the page everytime, is there anyway to print them in real time?,enter image description here
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var reload = require('reload');
var http = require('http');
var server = http.createServer(app);
var impares = 0;
var pares = 0;
var ninguno =0;
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.post('/arduino', function(request, response) {
console.log("Arduino asking data");
var stringInform = (Object.keys(request.body)).toString();
var stringA = stringInform.split("|");
var dato1= parseInt(stringA[0],10);
var dato2 = parseInt(stringA[1],10);
response.send('Hello Arduino');
Parimpar(dato1,dato2);
response.end();
console.log(dato1);
console.log(dato2);
console.log(ninguno);
});
app.get('/arduino', function(request, response) {
response.write('PARES:'+ pares + ' '+ 'IMPARES:' + impares + ' ' + 'NINGUNO:'+ ninguno);
response.end();
});
app.listen(8080);
function Parimpar(c,i)
{
if (c%2 == 0 && i%2 == 0)
{
pares = pares +1;
// return pares;
}
else if (c%2 != 0 && i%2 != 0)
{
impares = impares + 1;
//return impares;
}
else
{
ninguno = ninguno +1 ;
//return ninguno;
}
}
You Can Use Web-sockets To Emit Events When The Values Are Updated . The Easier Way Is to Setup A socket.io webserver and emit values to all the connected values.
Check Out https://socket.io/
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
}
});
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.
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);