Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
node js post request only works second time

I have one strange issue, when I submit form, it redirects to form action URL then it shows blank page. When I reload it again it will display the data.

index.jade - http://172.18.0.60:3000/

  form#command(action='runcommand', method='post')
    input#cmdls(type='checkbox', name='cmdls', value='ls -la')
    label(for='cmdls') List Files
    br
    input#cmdpwd(type='checkbox', name='cmdpwd', value='pwd')
    label(for='cmdpwd') Print Working Directory
    br
    input#cmddate(type='checkbox', name='cmddate', value='date')
    label(for='cmddate') Date
    br
    input.button(type='submit', value='Run')

app.js

var tmp=""; 
app.post('/runcommand',function(req,res){

    for (var key in req.body) {

            console.log(key);
            function puts(error, stdout, stderr) { sys.puts(stdout) }
            exec(req.body[key], function(error, stdout, stderr) {
              if (!error) {
                    tmp+=stdout;                       
              } else {
                tmp+=stderr;
              }
            });

    }

    res.render("result",{ data: tmp });

});

result.jade - http://172.18.0.60:3000/runcommand

extends layout

block content
    h1= "Result"   
    pre=  data

When I submit form it will redirect to http://172.18.0.60:3000/runcommand only displaying h1, when I reload it again it display data.

why it is behave like this?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

exec() is asynchronous so it finishes AFTER you call res.render(). So, you need to render only after all the exec() calls have finsished. This would probably be easier to code if you used promises and Promise.all() to keep track of when all the exec() calls were done, but you could also use a counter to know when the last one was done.

Here's a scheme using a counter:

app.post('/runcommand', function(req, res) {

    let keys = Object.keys(req.body);
    let cnt = 0;
    let tmp = '';
    if (!keys.length) {
        // render something when there were no keys
        res.render(...)
    } else {
        keys.forEach(function(key) {
            console.log(key);

            exec(req.body[key], function(error, stdout, stderr) {
                if (!error) {
                    tmp += stdout;
                } else {
                    tmp += stderr;
                }
                ++cnt;
                // if all exec calls have finished, the render
                if (cnt === keys.length) {
                    res.render("result", {data:tmp});
                }
            });
        });
    }
});

P.S. This code looks like it allows any client to run any arbitray program on the server (if it's in the path or they can construct the full path). That seems very dangerous.

P.P.S. Accumulating tmp outside the handler like you were doing in your original code is a disaster for multiple users using your server as multiple requests can tromp on either other's value in tmp. Accumulated data like this needs to either be in a local variable inside the request handler or in a property on the request object so that it can never conflict with other requests in process.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda