Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda