如何在回调函数中发送next()

时间:2019-02-27 03:20:11

标签: python node.js rest express npm

在这里,当我从python脚本接收到我的数据时,我想发送next(),但出现错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头。

const {PythonShell} = require('python-shell');

module.exports = (req, res, next)=>{
let myPythonScriptPath = 'encrypt.py';
const pyshell = new PythonShell(myPythonScriptPath);
let path = req.file.path;    
pyshell.send(path);


pyshell.on("message", function(data){
    console.log(data);
    req.filepath = data;
    next();
})

// end the input stream and allow the process to exit
pyshell.end(function (err) {
    if (err){
        throw err;
    }
});
}

但是当我将next()放在代码末尾但我的req.filepath未定义

时,它可以工作
const {PythonShell} = require('python-shell');

module.exports = (req, res, next)=>{
let myPythonScriptPath = 'encrypt.py';
const pyshell = new PythonShell(myPythonScriptPath);
let path = req.file.path;    
pyshell.send(path);


pyshell.on("message", function(data){
    console.log(data);
    req.filepath = data;
})

// end the input stream and allow the process to exit
pyshell.end(function (err) {
    if (err){
        throw err;
    }
});

next();
}

我想要的是将来自python脚本的数据存储在req.filepath中,该数据将发送到下一个中​​间件。有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

由于异步任务的顺序,您正在看到此行为,我在下面的注释中已对其进行了枚举。执行不一定按照编写代码的顺序进行,因此,您要么尝试在发送PyShell命令后修改 的请求/响应(上述案例1) ),或者Express已在设置req.filepath之前移至下一个中间件(上述情况2)。

const {PythonShell} = require('python-shell');

module.exports = (req, res, next) => {
  let myPythonScriptPath = 'encrypt.py';
  const pyshell = new PythonShell(myPythonScriptPath);
  let path = req.file.path;
  pyshell.send(path); // 1) Send the command

  // 3) This anonymous function is invoked, but it's
  // too late -- the command has already been sent
  // and has continued on to the next middleware.
  pyshell.on("message", function(data){
    console.log(data);
    // This will be undefined in the next middleware
    // because it moved on before it was actually set.
    req.filepath = data;
  })

  // 4) This anonymous function gets run last.
  pyshell.end(function (err) {
    if (err){
        throw err;
    }
  });

  next() // 2) Tell Express to continue on to the next middleware.
}

在尝试修改或发送HTTP响应的中间件之前或之后,您还有其他中间件吗?

答案 1 :(得分:0)

使用回调方法可以通过在callback()中发送函数的结果来实现。(这里是回调)

代码如下:

const {PythonShell} = require('python-shell');

module.exports = function (req, res, next){
try{
    let myPythonScriptPath = '/home/anmolmiddha/Projects/coreshare/server/api/python/encrypt.py';
    const pyshell = new PythonShell(myPythonScriptPath);
    let path = req.file.path;
    pyshell.send(path);
    pyshell.on("message", function(data){
    });

    pyshell.end(function (err, rslt) {
        if(err){
            res.status(500).json(err);
        }
        else{
            req.filepath = JSON.stringify(path).split('"')[1];
            next(rslt);
        }
    });
}
catch(error) {
    return res.status(401).json({
        message: "Invalid token Auth failed"
    })
}
}