1

I have a python code and I call it in nodejs. The python code will print a sentence at different stage. After each print in python there is a sys.stdout.flush(). Now I use nodejs python shell

app.post('/', function (req, res) {
  flag = req.body.flag;
  options = {
    mode: 'text',
    args: [ '--flag='+flag]
  };

  pyshell = new PythonShell(myPythonScriptPath, options)

  pyshell.on('message', function (message) {   
    resultText = `It's ${flag} degrees in ${message}!`;
    res.render('index', {result: resultText, error: null});
    console.log(message);
  })
})

It returned only one sentence and after that there was an error: Error: Can't set headers after they are sent.

This worked fine if I do not use

resultText = `It's ${flag} degrees in ${message}!`;
res.render('index', {result: resultText, error: null});

and only use terminal. BUT it fails with a web page. Does anyone know how to solve this?

rtn
  • 127,556
  • 20
  • 111
  • 121
ZHANG Juenjie
  • 501
  • 5
  • 20

1 Answers1

1

From community wiki's answer:

The res object in Express is a subclass of Node.js's http.ServerResponse (read the http.js source). You are allowed to call res.setHeader(name, value) as often as you want until you call res.writeHead(statusCode). After writeHead, the headers are baked in and you can only call res.write(data), and finally res.end(data).

The error "Error: Can't set headers after they are sent." means that you're already in the Body or Finished state, but some function tried to set a header or statusCode. When you see this error, try to look for anything that tries to send a header after some of the body has already been written. For example, look for callbacks that are accidentally called twice, or any error that happens after the body is sent.

mdegis
  • 2,078
  • 2
  • 21
  • 39