Reputation: 1390
I am simply using the Stripe API to create a subscription in firebase cloud functions.
I am getting the errors: Unhandled rejection Error: Can't set headers after they are sent.
Here is my index.ts:
export const subscribe = functions.https.onRequest((req, res) => {
res.header('Content-Type','application/json');
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
//respond to CORS preflight requests
if (req.method == 'OPTIONS') {
res.status(204).send('');
}
stripe.subscriptions.create({
customer: req.body.sid,
items: [
{
plan: "plan_123123123",
},
]
}, function(err, subscription) {
// asynchronously called
if (err) {
return res.send(err)
}
else {
return res.send(subscription)
}
}
);
});
Upvotes: 1
Views: 77
Reputation: 1318
Instead of
if (req.method == 'OPTIONS') {
res.status(204).send('');
}
try:
if (req.method == 'OPTIONS') {
return res.status(204).send('');
}
otherwise, you'll be calling res.send()
twice in case of OPTIONS (pre-flight) request, causing the error.
Upvotes: 1