Express res.write() 方法仅在第一次有效,但随后无效

问题描述

我有一个服务器代码,我需要运行它并不断向前端发送数据以供客户端使用。但是, res.write() 方法仅适用于发送由字符串化 JSON 组成的第一个响应,并且不会发送所有后续响应。我在 express 上使用 post 路由来执行任务,因为它涉及客户端在执行任务之前向服务器端发送一些数据:

请看下面我的代码: 客户端.js

$('#submit').on('click',(event) => {
  $.ajax({
      url: '/filePathSubmit',type: 'POST',contentType: 'application/json',data: JSON.stringify({
        "excelFileFT": submittedFTFilepath,"excelFilePT": submittedPTFilepath,"outputDirectory": submittedOutputDirectory
      }),success: (response) => {
        console.log("Data successfully posted:");
        console.log(response);
      }
  });
});

server.js

server.post('/filePathSubmit',(req,res) => {
    var excelFileFT = req.body.excelFileFT;
    var excelFilePT = req.body.excelFilePT;
    var outputDirectory = req.body.outputDirectory;

    res.write(JSON.stringify(req.body,null,2)) //this is the only response that appeared on client side
    
    let options = {
        mode: 'text',pythonPath: './pyFiles/env/Scripts/python.exe',pythonoptions: ['-u'],// get print results in real-time
        scriptPath: './pyFiles',args: [excelFileFT,excelFilePT,outputDirectory]
    };

    let pyshell = new PythonShell('payroll_report2.py',options);

    pyshell.on('message',message => {
        // received a message sent from the Python script (a simple "print" statement)
        console.log(message);
        res.write(message);
    });
    
    pyshell.end((err,code,signal) => {
        if (err) throw err;
        console.log('The exit code was: ' + code);
        console.log('The exit signal was: ' + signal);
        console.log('finished');
        res.end() // res.end is inserted here so that this method will only be called when the sequence have completed
    });
})

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)