【问题标题】:How can I use the amount variable outside this function please can any one help me我如何在这个函数之外使用数量变量请任何人帮助我
【发布时间】:2021-09-09 15:09:39
【问题描述】:

请谁能告诉我如何在此函数之外获取我从req.body 获取的数量变量或其数据?

app.post("/pay", (req, res) => {
  console.log(req.body); 
  const { amount , description , name } = req.body;    //this is that amount variable
  const create_payment_json = {
    intent: "sale",
    payer: {
      payment_method: "paypal",
    },
    redirect_urls: {
      return_url: "http://localhost:3000/success",
      cancel_url: "http://localhost:3000/cancel",
    },
    transactions: [
      {
        item_list: {
          items: [
            {
              name: name,
              sku: "001",
              price: amount,
              currency: "USD",
              quantity: 1,
            },
          ],
        },
        amount: {
          currency: "USD",
          total: amount,
        },
        description: description,
      },
    ],
  };

  paypal.payment.create(create_payment_json, function (error, payment) {
    if (error) {
      throw error;
    } else {
      for (let i = 0; i < payment.links.length; i++) {
        if (payment.links[i].rel === "approval_url") {
          res.redirect(payment.links[i].href);
        }
      }
    }
  });
});

app.get("/success", (req, res) => {
  const payerId = req.query.PayerID;
  const paymentId = req.query.paymentId;

  const execute_payment_json = {
    payer_id: payerId,
    transactions: [
      {
        amount: {
          currency: "USD",
          total: amount,    // I want it here also
        },
      },
    ],
  };

  paypal.payment.execute(
    paymentId,
    execute_payment_json,
    function (error, payment) {
      if (error) {
        console.log(error.response);
        ;
      } else {
        console.log(JSON.stringify(payment));
        res.send("Success");
      }
    }
  );
});

【问题讨论】:

  • 我不太明白。这是一个看起来像快速服务器的请求回调。您还希望在哪里使用请求数据?显示实际调用 fetch 的客户端函数(如果这是您要问的)。
  • @zero298 如果你能帮助我,我有评论我现在想要那个数量的可变数据
  • 你能不能说明你想如何在这个函数之外使用它?我们不需要大量的细节,但我们确实需要minimal reproducible example
  • 我想使用 app.get("/success", (req, res)) 中的值

标签: javascript node.js express


【解决方案1】:

您的问题还不清楚,但您似乎只想从响应回调外部访问amount。如果它像那样简单,你只需要在更高的范围内为它找到一个位置。例如,我要将所有付款存储在 payments 数组中。我还将“ammount”重命名为“amount”(拼写错误)。

每当向app.post("/pay") 发送POST 时,我们都会推送付款。 paymentsapp.get("/success") 可用,因为它位于更高的范围内。

如果这不是您想要做的,您需要为您的问题添加更多详细信息,并准确解释什么不起作用。

index.js

import express from "express";

const app = express();

const payments = [];

app.use(express.json());

app.get("/", (req, res) => {
  res.send("Hello world");
});

app.get("/success", (req, res) => {
  console.log(`There have been ${payments.length} payments`);
  if (payments.length) {
    const {person, amount, time} = payments[payments.length - 1];
    console.log(`Last payment was ${amount} by ${person} @ ${time}`);
  }
  res.sendStatus(200);
});

app.post("/pay", (req, res) => {
  const {person, amount} = req.body;
  const time = Date.now();

  payments.push({person, amount, time});
  console.log(`${person} paid ${amount} @ ${time}`);

  res.sendStatus(200);
});

app.listen(3002, () => {
  console.log("Listening");
});

这是我用来测试的文件。它使用node-fetch 作为fetch polyfill。

test.js

import fetch from "node-fetch";

const sleep = (t=1000) => new Promise(r => setTimeout(r, t));

const main = async () => {
  const payResponse = await fetch("http://localhost:3002/pay", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      person: "Bob Barker",
      amount: 500
    })
  });

  await sleep();

  const checkResponse = await fetch("http://localhost:3002/success");
};

main()
  .then(() => console.log("Done"))
  .catch(err => console.error(err));

运行它会产生这个:

Listening
Bob Barker paid 500 @ 1631202912836
There have been 1 payments
Last payment was 500 by Bob Barker @ 1631202912836

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 2022-11-10
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多