Imran
Imran

Reputation: 1

CORS issue when call Supabase edge function

I have integrated a PayPal button on my website to handle subscription payments. When the payment is approved, I need to send the subscription details to a Supabase edge function to update my database. However, I'm encountering a CORS (Cross-Origin Resource Sharing) error. Here are the details of the issue:

Access to fetch at 'https://olxxxxxxxjyvrmgail.supabase.co/functions/v1/paypal_ex' from origin 'https://mywebsite.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Note that I added the CORS headers in my function :

///....

const corsHeaders = {
  'Access-Control-Allow-Origin': 'https://mywebsite.com', 
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

//...

const handler = async (request: ServerRequest): Promise<Response> => {
  if (request.method === 'OPTIONS') {
    return new Response(null, {
      status: 200,
      headers: corsHeaders,
    });
  }

  try {
    if (request.method !== 'POST') {
      throw new Error('Unauthorized method');
    }


    // Code.....
 
    return new Response(JSON.stringify(data), {
      status: 200,
      headers: {
        ...corsHeaders,
        'Content-Type': 'application/json',
      },
    });
  } catch (error) {
    console.error('Error:', error);

    return new Response(JSON.stringify({ error: error.message }), {
      status: 500,
      headers: {
        ...corsHeaders,
        'Content-Type': 'application/json',
      },
    });
  }
};


serve(async (req) => {
  // Gérer les requêtes OPTIONS pour CORS
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders });
  }

  return handler(req);
});

Thank you for your help

Upvotes: 0

Views: 117

Answers (0)

Related Questions