單擊前端的按鈕后,我想執行一個需要 10 到 30 秒才能運行的 python 腳本。
我試圖在我的后路由/控制器中呼叫 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));
});
});
uj5u.com熱心網友回復:
之所以顯示該錯誤,是因為您正在發送資料的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
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/401243.html
上一篇:C#多用戶TCP服務器
