【问题标题】:Wait for a python script to run before sending a response Node Express在发送响应之前等待 python 脚本运行 Node Express
【发布时间】:2022-01-01 09:51:11
【问题描述】:

点击前端的按钮后,我想执行一个 python 脚本,运行时间在 10 到 30 秒之间。

我正在尝试在我的发布路由/控制器中调用 python 脚本,但收到以下错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

在脚本运行之前,我不想向客户端发送任何内容。

路由/控制器:

const express = require("express");
const router = express.Router();

router.post("/solve", async function (req, res) {
  const board = JSON.stringify({
    board: req.body.grid,
  });

  const spawn = require("child_process").spawn;
  const pythonProcess = spawn("python", ["./crossword/crossword.py", board]);
  pythonProcess.stdout.on("data", (data) => {
    // Do something with the data returned from python script
    solved_data = JSON.parse(data.toString());
    res.send(JSON.stringify(solved_data));
  });
});

【问题讨论】:

    标签: python node.js express asynchronous


    【解决方案1】:

    显示错误是因为您在 data 事件中发送数据,该事件在每次输出更改时都会通过 python 脚本不断触发,该脚本重复向客户端发送响应(这不好),以解决您应该发送的问题只响应一次,为此您应该订阅进程的退出事件,以便收集所有输出,然后在进程关闭时将输出作为响应发送

    const express = require("express");
    const router = express.Router();
    let data = '';
    
    router.post("/solve", async function (req, res) {
      const board = JSON.stringify({
        board: req.body.grid,
      });
    
      const spawn = require("child_process").spawn;
      const pythonProcess = spawn("python", ["./crossword/crossword.py", board]);
      pythonProcess.stdout.on("data", (response) => {
        // Keep collecting the data from python script
        data += response;
      });
    
      pythonProcess.on('exit', function(code, signal) {
        console.log('Python process is now completed send data as response');
        let solved_data = JSON.parse(data);
        res.send(JSON.stringify(solved_data));
        //you can also check code to verify if exit was due to error or normal
      });
    });
    

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多