Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!