Get QueryString with NodeJS

2

I need to get the QueryString being passed to the server created on NodeJS . I've tried it in many ways but I can not get the and ph parameters. I am a beginner in NodeJS and the code I have is:

var express = require('express')
  , app = express()
  , fs = require('fs')
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server)
;

app.use(express.static(__dirname + '/'));

var porta = 3000;

app.get('/', function (req, res) {

  res.sendFile(__dirname + '/index.html')

});

io.on('connection', function(socket){

  result = {
          ph: Math.random() * 100,
          DO: Math.random() * 100
        }

  /*socket.emit('dados', {
    valor: result
  });*/

  socket.broadcast.emit('dados', {
    valor: result
  });


});


server.listen(porta, function(){
  console.log("Servidor rodando na porta "+porta+". Aperte CTRL+C para finalizar a conexão.");
});

I need to get this data that is going to be passed by QueryString and play in json result instead of Math.random() * 100

    
asked by anonymous 26.11.2016 / 09:20

1 answer

1

I found an idea here that can be applied here:

var ligacoes = {};
var queryString = {};

app.get('/', function(req, res) {
    queryString.do = req.query.do;
    queryString.ph = req.query.ph;
    res.sendFile(__dirname + '/index.html')
});

io.on('connection', function(socket) {
    if (!ligacoes[socket.id]) ligacoes[socket.id] = JSON.parse(JSON.stringify(queryString));
    var result = {
        ph: ligacoes[socket.id].ph,
        DO: ligacoes[socket.id].do
    }

    socket.emit('dados', {
        valor: result
    });

    socket.broadcast.emit('dados', {
        valor: result
    });
    socket.on('disconnect', function() {
        delete ligacoes[socket.id];
    });
});

In this way an entry is created for each socket in a ligacoes object, and each time that entry is created it copies the values that queryString has and maintains them for that connection.

    
27.11.2016 / 09:05