Home
Support Forums

Running Netlify functions locally

Hi, when I try to run my netlify fuctions locally using Netlify- Dev I get a cross-origin error. What is the simplest way to fix this? This is error message

This is from network tab-
image

This is the netlify function
exports.handler = async (event, context) => {

const stripe = require('stripe')(process.env.REACT_APP_STRIPE_SK);

var info = JSON.parse(event.body);

const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
        {
            price_data: {
                currency: 'usd',
                product_data: {
                    name: `Pies: ${info.pies} Fries: ${info.fries} `,

                },
                unit_amount: info.total * 100,
            },
            quantity: 1,
        },
    ],
    mode: 'payment',
    success_url: `https://pies-and-fries.netlify.app`,
    cancel_url: 'https://pies-and-fries.netlify.app?info=canceled',
});
console.log("hi from func")
const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE'
};


return {
    statusCode: 200,
    headers,
    body: JSON.stringify({
        sessionId: session.id,
        orderInfo: info
    }),

}

}
This is the code that calls the function

     const stripe = await stripePromise;

    const response = await fetch("https://pies-and-fries.netlify.app/.netlify/functions/acceptPayment", {

        method: 'POST', headers: {

            'Content-Type': 'application/json',

            'Access-Control-Allow-Origin': '*',

            'Access-Control-Allow-Headers': 'Content-Type',

            'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE'

        },

        body: JSON.stringify(abbreviatedState)

    });

    const session = await response.json();

    // When the customer clicks on the button, redirect them to Checkout.

    const result = await stripe.redirectToCheckout({

        sessionId: session.sessionId

    });

    result.then(() => {

        console.log(JSON.stringify(result))

    })

    if (result.error) {

        console.log(result.error.message)

        // If `redirectToCheckout` fails due to a browser or network

        // error, display the localized error message to your customer

        // using `result.error.message`.

    }

    //this.props.methodToPassToChild('confirmed');

}

Any help would be appreciated- it would be great to be able to make changes without pushing them to production. My site is https://pies-and-fries.netlify.app/

When calling fetch have you tried calling /.netlify/functions/acceptPayment without the absolute url? I think netlify dev includes a built in proxy to the functions run on port 8888

1 Like

glad to help :slight_smile: I faced these same issues