首页 > 解决方案 > node.js 中的 HTTP POST 请求之前如何做一些事情?

问题描述

我对nodejs很陌生,我尝试将带有一些数据的图像上传到nodejs API,但是在将数据保存到Mongo DB之前,我尝试使用Python类对这个上传的图像进行一些处理,然后我会将结果保存到DB

所以我可以将上传的图像发送到 python 代码并在将任何数据保存到数据库之前等待结果

我的代码在这里

  router.post('/img2text', upload.single('photo'), (req, res) => {
    // Create the object for insertion into database
    const Img2text = new img2text({
      imgPath: req.file.path,
      sender: req.body.sender,
      processed: 0,
      resultText: "no result",
    });
/////////////////////////////////////////////////////////////start
    var exec = require("child_process").exec;
    exec(`python uploads/hello.py ${req.file.path}`,(error, stdout, stderr) => {
      if (error) {
        Img2text.processed=0;
        Img2text.resultText='no result'
        console.error(`exec error: ${error}`);
        return;
      }
      console.log(`stdout: ${stdout}`);
      Img2text.processed=1;
      Img2text.resultText=stdout.toString('utf8');
      console.log(`stderr: ${stderr}`);
      console.log(req.query.firstname);
    });
    /////////////////////////////////////////////////////////end

    // Save  into database
    Img2text.save((err) => {
      // Check if error
      if (err) {
        res.json({ success: false, message: err });
      } else {
        console.log("img saved !!")
        res.json({ success: true, message:img.resultText }); // Return success message
      }
    });
  });

如果 python 代码需要很长时间,我的对象会是空的吗?


任何答案将不胜感激


标签: pythonnode.jsexpress

解决方案


你有没有试过使用Promise,如果没有参考这个链接Promise MDN。只需将您的流程包装在 a 中Promise,当您完成流程后解决它并将其保存到数据库中。

router.post('/img2text', upload.single('photo'), (req, res) => {
        // Receive your image

        let pythonProcess = new Promise((resolve, reject)=>{
         // do your process
         reolve() // resolve with updated data
        })
        pythonProcess.then(img =>{
         //save to db
        })
   })

现在,在您最好的情况下,我更喜欢使用aync/await Async/await MDN。不要把它当作另一种方式来做,它只是现代的使用方式promise。作为内部await也设置promise链。你有两种选择,要么你可以通过它,promises你会得到最好的东西之一,javascript 或者如果你想要一小段代码await

router.post('/img2text', upload.single('photo'), async(req, res) => { // To use await function need to be a async function
    // Create the object for insertion into database
    const Img2text = new img2text({
      imgPath: req.file.path,
      sender: req.body.sender,
      processed: 0,
      resultText: "no result",
    });
/////////////////////////////////////////////////////////////start
    var exec = require("child_process").exec;
    await exec(`python uploads/hello.py ${req.file.path}`,(error, stdout, stderr) => {
      if (error) {
        Img2text.processed=0;
        Img2text.resultText='no result'
        console.error(`exec error: ${error}`);
        return;
      }
      console.log(`stdout: ${stdout}`);
      Img2text.processed=1;
      Img2text.resultText=stdout.toString('utf8');
      console.log(`stderr: ${stderr}`);
      console.log(req.query.firstname);
    });
    /////////////////////////////////////////////////////////end

    // Save  into database
    Img2text.save((err) => {
      // Check if error
      if (err) {
        res.json({ success: false, message: err });
      } else {
        console.log("img saved !!")
        res.json({ success: true, message:img.resultText }); // Return success message
      }
    });
  });

推荐阅读