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

时间:2018-10-04 09:26:23

标签: php node.js parameter-passing

我有一个php文件和Node API。服务器中的php文件,该文件按用户指定的最大值返回随机数。给定的maximun值用户是从Node Js到php。然后php返回随机值,然后将这些值保存在MongoDB中

php代码

<?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;
?>

节点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 个答案:

答案 0 :(得分:0)

您为什么不使用axios。尝试此代码,希望可以按您的意愿工作

节点

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();
    }
?>