ee e
ee e

Reputation: 71

Javascript - Response to preflight request doesn't pass access control check

I am trying to create a checkout session for stripe like the docs say to do, but I am getting this error:

Access to fetch at 'https://subdomain' from origin 'https://main-domain' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Where and how should I add the specified header?

This is the request sent when the checkout button is clicked:

<script type="text/javascript">
   var stripe = Stripe('api key');
   var checkoutButton = document.getElementById('checkout-button');
   
   checkoutButton.addEventListener('click', function() {
     fetch('https://subdomain/create-session', {
       method: 'POST',
       headers: new Headers({
       'Authorization': 'Basic',
       'Access-Control-Allow-Origin': '*'
       })
     })
     .then(function(response) {
       return response.json();
     })
     .then(function(session) {
       return stripe.redirectToCheckout({ sessionId: session.id });
     })
     .then(function(result) {
       if (result.error) {
         alert(result.error.message);
       }
     })
     .catch(function(error) {
       console.error('Error:', error);
     });
   });
</script>

This is my express route:

app.post("/create-checkout-session", async (req, res) => {
    const session = await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        line_items: [
            { price: 'stripe product id', quantity: 1 },
            { price: 'stripe product id', quantity: 1 }
        ],
        mode: 'payment',
        success_url: 'https://site/success.html',
        cancel_url: 'https://site/cancel.html',
    });
    res.json({ id: session.id });
});

Upvotes: 1

Views: 1560

Answers (1)

syberen
syberen

Reputation: 679

The header should be included in the server response, not the client request. With express you can use the CORS middleware for this.

Upvotes: 2

Related Questions