异步块中的res.sendStatus()

时间:2018-02-21 21:49:17

标签: javascript node.js express

我试图在异步块内发回成功代码,但收到错误:Unhandled rejection Error: Can't set headers after they are sent.

stripe.charges.create({
    amount: booking.currentPrice,
    currency: "usd",
    source: "tok_visa_debit",
    destination: {
      account: booking.hostUser.stripeAccountId,
    },
}).then(function(charge, err) {
    // asynchronously called
    res.sendStatus(200); // causes error
});

res.sendStatus(500);

如何在此异步块中指示成功?

1 个答案:

答案 0 :(得分:0)

无论结果如何,您似乎都在发送500状态,这意味着它可能在调用成功处理程序之前发送。

您应该只在发生错误时发送错误状态。

stripe.charges.create({
    amount: booking.currentPrice,
    currency: "usd",
    source: "tok_visa_debit",
    destination: {
        account: booking.hostUser.stripeAccountId,
    },
}).then(function(charge) {
        // asynchronously called
        res.sendStatus(200); // causes error
}).catch(function(error) {
    console.log(error);
    res.sendStatus(500);
}) ;