dongling0519 2018-10-04 09:26
浏览 118
已采纳

如何将Node Js中的值传递给php然后返回?

I have a php file and Node API. The php file in server which return the random number by user given max value. The user given maximun value is given from Node Js to php. Then the php returns the random value, then the values should be save in MongoDB

php code

<?php
    $min = 1111;
    $max = '';  // This is given by user from Node API

    $number = mt_rand($min, $max); //Generate a random number using the rand function.

    echo $number;
?>

Node API

router.post("/findMax", upload.single('image'), function (req, res, next)
{
  var enteredMaxNum = req.body.maxNum;
  if(!enteredMaxNum)
  {
    return res.status(400).send("Maximum number should be given");
  }

  const objNumber = new Number(
    {
      max : enteredMaxNum,  // User given, should pass to php variable
      randNum : ????,       // php file return value
    });

    objNumber.save((err) =>
      {
        if (err)
        {
          console.log("New Error : " + err);
          return next(err);
        }
        res.status(201).send("Numbers saved");
      });
})
  • 写回答

1条回答 默认 最新

  • dongzhi1822 2018-11-15 18:17
    关注

    Why did not you use axios. Try this code hopefully will work as you want

    node

    router.post("/findMax", upload.single('image'), function (req, res, next)
    {
      var enteredMaxNum = req.body.maxNum;
      if(!enteredMaxNum)
      {
        return res.status(400).send("Maximum number should be given");
      }
    
      axios.post('your-php-file-path', require('querystring').stringify({getNodeNum: enteredMaxNum}))
      .then(response => {
        if (response)
        {
          const objNumber = new Number({max: enteredMaxNum, randNum: response.data.random});
          objNumber.save((err) => {
            if (err)
            {
              console.log("New Error : " + err);
              res.status(500).send(err);
            }
            res.status(201).send("Numbers saved");
            });
        }
          })
      .catch(error => res.status(500).send(error));
    })
    

    php

    <?php
    
        $min = 1111;
    
        if(isset($_POST['getNodeNum'])) // It should be $_POST
        {
            $max = $_POST['getNodeNum'];
    
            $number = mt_rand($min, $max);
    
            print(json_encode(['random' => $number]));
            exit();
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗