簡體   English   中英

Node.js中的post方法

[英]Post method in Node.js

我需要一些關於 post 方法的幫助。

這是我使用 stripe 進行一些卡支付的 post 方法

app.post('/charge', (req, res) => {
  const amount = 2500;
  stripe.customers
    .create({
      email: req.body.stripeEmail,
      source: req.body.stripeToken,
    })
    .then((customer) =>
      stripe.charges.create({
        amount,
        description: 'Web Development eBook',
        currency: 'usd',
        customer: customer.id,
      })
    )
    .then((charge) => res.render('success'));
});

在相同的方法中,我想添加以下方法,該方法目前僅適用於 postman


exports.addTransaction = async (req, res, next) => {
  try {
    const { text, amount } = req.body;

    const transaction = await Transactions.create(req.body);

    return res.status(201).json({
      success: true,
      data: transaction,
    });
  } catch (err) {
    return res.status(500).json({
      success: false,
      error: 'Server Error! Transaction was not added',
    });
  }
};

我想通過 POST 方法發送的正文是這樣的

{
    "text": "Book",
    "amount": -23
}

我認為您對 async/await 示例感到困惑。 async/await 語法適用於 promise,就像then的 function 一樣, await等待 function 執行並將數據返回到等待相同的變量。

考慮以下示例來檢查 async/await 和 promise 語法之間的區別

function myPromise() {
   return new Promise((resolve, reject) => {
      resolve(5);
   });
}

現在,我們可以用兩種不同的語法調用上面的 function

myPromise.then((data) => {
  console.log(data); // prints 5
});

或者,我們可以像這樣使用現代async/await

const data = await myPromise();

上面的 function 只有在它被包裝的 function 開頭有async的情況下才有效。

例如:

async function getData() {
  const data = await myPromise();
  console.log(data);
}

請注意function關鍵字之前的async關鍵字,如果沒有async關鍵字,function 將無法工作。

另外,就像常規 promise 中的catch一樣,我們使用try/catch來捕獲錯誤。

現在,回到您的問題,您可以將第二個 function 轉換為使用then().catch()順序,或者您可以將第一個 function 轉換為使用async/await樣式。 或者您可以結合使用兩者。

下面,我在你的第一個 function 中實現了你的第二個 function 的then/catch版本

app.post('/charge', (req, res) => {
  const { text, amount } = req.body;
  stripe.customers
    .create({
      email: req.body.stripeEmail,
      source: req.body.stripeToken,
    })
    .then((customer) =>
      stripe.charges.create({
      amount,
      description: 'Web Development eBook',
      currency: 'usd',
      customer: customer.id,
  });
)
.then((charge) => {
    Transactions.create(req.body).then(() => {
       res.status(201).json({
       success: true,
       data: transaction,
      });
    }).catch((e) => {
       res.status(500).json({
       success: false,
       error: 'Server Error! Transaction was not added',
      });
    });
});

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM