【问题标题】:return value from python-shell as response从 python-shell 返回值作为响应
【发布时间】:2019-01-06 07:52:58
【问题描述】:

我正在使用 python shell 在 nodeJS 上运行 python。我需要返回 python shell 作为响应。但是当我尝试发送响应时它显示错误

Can't set headers after they are sent.

这是我的代码

app.post('/therun', (req, res)=>{

    var pyshell = new PythonShell('hello.py');

    pyshell.on('message', function (message) {

       console.log(message); //value is correct
       res.send(message); //error here

      });

       res.send(message); //if i use here message undefined


});

如何解决这个问题?

【问题讨论】:

    标签: python json node.js angular flask


    【解决方案1】:
        app.post('/therun', (req, res)=>{
    
        var pyshell = new PythonShell('hello.py');
        var test={};
    
        pyshell.on('message', function (message) {
    
           console.log(message); //value is correct
           //res.send(message); //error here
          test=message;
    
          });
           console.log(test);
           res.send(message); //if i use here message undefined
    
    
    });
    

    您能告诉我控制台上对 test 值的响应吗?

    【讨论】:

    • @LVW23 你能改变这一行 test=message;到 this.test=message 并让我知道它之后的日志?另外,如果您可以分享,您的 console.log(message) 在输出中给出的内容将有助于澄清一些事情
    • 节点不是问题,我想在运行这段代码时进行一些观察 1) 你的 console.log(message) 是否以 json 格式出现 2) 如果消息被正确填充,那么响应是否正确? @LVW23
    【解决方案2】:

    而不是将其发送为,

    res.send(message); //error here
    

    您可以尝试使用下面给出的状态代码发送相同的内容吗?

    res.status(200).json({
      "message":message
    })
    

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      你忘了关闭 python shell(在 pyshell.on() 之后):

      pyshell.end(function (err) {
        if (err) throw err;
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-13
        • 2021-04-03
        • 2016-01-01
        • 2021-03-24
        • 2019-03-16
        • 1970-01-01
        • 2020-09-12
        • 1970-01-01
        相关资源
        最近更新 更多