[英]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.