Catch Querystring with Nodejs

Asked

Viewed 653 times

2

I need to pick up the QueryString which is being passed to the server created on Nodejs. I’ve tried several ways but I can’t get the parameters of and Ph. I’m a beginner at 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 take these dice that will be passed through Querystring and play on json result in place of Math.random() * 100

  • Where’s that coming from querystring? how do you upload this in the browser?

  • http://localhost:3000/? do=30&pa=10 ... I need to get these 2 querystring in the app.js which is the code I posted, but I don’t know which module I use and how to use it

  • The API is var foo = req.query.nomeDaChave;, and you could do like this: https://jsfiddle.net/t4gpf3ys/ the problem is that different users change this global... these values of do and ph are static or change?

  • @Sergio they change every 5 seconds

1 answer

1

I found an idea here which 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];
    });
});

This way you create an input for each socket in an object ligacoes, and each time this input is created it copies the values that queryString has and maintains them for that connection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.