Store app.post nodejs request data

Asked

Viewed 655 times

0

Speak people, I would like to know how I can use the data received from the page to use outside the app.?

var SerialPort = require('serialport');
var Readline = SerialPort.parsers.Readline;
var methodOverride = require('method-override');


//faz requerimento dos modulos
var serveStatic = require('serve-static');
const express = require('express');
const socketIo = require('socket.io');
const http = require('http');
var path = require('path');

//cria servidor
const app = express();
const server = http.createServer(app);
const io = socketIo.listen(server);

//starta servidor na porta 3000
server.listen(3000, () => {
	console.log('Servidor Online na porta 3000');
});

//define um diretorio commo public para acesso as propriedades
app.use(serveStatic(path.join(__dirname, 'public'), {
	maxAge: '1d'
	}));

// retorna index quano recebe requição
app.get('/', (req, res, next) => {
	res.sendFile(__dirname + '/index.html');
	app.use(serveStatic(path.join(__dirname, 'public'), {
		maxAge: '1d'
		}));
});

var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.route('/signup');
app.post( '/signup', urlencodedParser, function(req, res) {
	var portCOM = req.body.portCOM;
	var bauRATE = req.body.bauRATE;
	res.json(
		{ 
		   	message: 'signup success',
			portCOM : portCOM,
			bauRATE : bauRATE,
		}
	);
});

app.get(function(req,res){
	res.json({message: 'get request from signup'});
});

// configurações da comunicação serial
port = new SerialPort(portCOM, {
	baudRate: 9600,
    dataBits: 8,
    paridade: 'nenhum' ,
    stopBits: 1,
    flowControl: false ,
    parser: new SerialPort.parsers.Readline('\r') 	
});

//define um limite para acionar um evento
const ByteLength = require('@serialport/parser-byte-length');
const parser = port.pipe(new ByteLength({length: 4}));

//EXIBE OS LOG NO TERMINAL, INFORMAÇOES VINDA DO ARDUINO
port.open(function()
{
	console.log('Porta aberta');
});

var ModbusTCP = "";
parser.on('data', function (data)
{		
		ModbusTCP = data.toString();
		ModbusTCP = ModbusTCP.replace(/(\r\n|\n|\r)/gm,"");	
		var infLeng = ModbusTCP.length;		
		
		console.log('tamanho do envio:',infLeng);
		console.log('Valor Hexadeciaml: ' + ModbusTCP);
});

  • Isn’t it enough to just call a function by passing req? Or maybe what you want to do is capture and treat these arguments before you arrive in the app.post with a middleware? Can you describe what you’re trying to do?

  • I’m going through some parameters on the client side to connect to a serial port, so I need to take these parameters that are stored inside the app.post and treat them outside the app.post

  • when I try to use the portCOM variable outside the app.post I have the return portCOM is not defined.

  • I still don’t understand what the difficulty is. Don’t just send portCOM or res as parameter to another function? You can edit your question by posting the full code, including the part that gives error?

  • posted the complete code, in the part that configure the connection to the port COM I can not use the variable.

1 answer

1


As far as I can tell, portCOM is used in SerialPort, but SerialPort is not being called through a middleware, it is directly at the root of the script, which means it will run only once when the server is started, even before the user sends the value of portCOM.

To execute SerialPort only when repurchase is sent to the route signup, you need to put or call the code within the callback function of the route:

app.post('/signup', urlencodedParser, function (req, res) {
    const portCOM = req.body.portCOM;
    const bauRATE = req.body.bauRATE;

    criarPorta(portCOM);

    res.json({
        message: 'signup success',
        portCOM: portCOM,
        bauRATE: bauRATE,
    });
});

function criarPorta(portCOM) {
    port = new SerialPort(portCOM, {
        baudRate: 9600,
        dataBits: 8,
        paridade: 'nenhum',
        stopBits: 1,
        flowControl: false,
        parser: new SerialPort.parsers.Readline('\r')
    });

    // .
    // .
    // .
    // Restante do código
}

Or else use the code as middleware:

app.post('/signup', urlencodedParser, criarPorta, function (req, res) {
    const portCOM = req.body.portCOM;
    const bauRATE = req.body.bauRATE;

    res.json({
        message: 'signup success',
        portCOM: portCOM,
        bauRATE: bauRATE,
    });
});

function criarPorta(req, res, next) {
    const portCOM = req.body.portCOM;

    port = new SerialPort(portCOM, {
        baudRate: 9600,
        dataBits: 8,
        paridade: 'nenhum',
        stopBits: 1,
        flowControl: false,
        parser: new SerialPort.parsers.Readline('\r')
    });

    // .
    // .
    // .
    // Restante do código

    next();
}
  • showww thank you so much, I had done different, I had put inside the main middleware app.post and it worked, but your method is the correct and most stable.

  • The stability is the same, just a little more organized. I’ll give a hint that I ended up not leaving in the answer: you can use the middleware urlencodedParser before the route declaration, this way you don’t need to manually declare it on all routes you create. Just put app.use(urlencodedParser) above the route declaration, and the body parse of the requests will be done in the same way.

Browser other questions tagged

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