如何解决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 举报,一经查实,本站将立刻删除。