Access to fetch at $AWS_LAMBDA_SITE from origin 'http://localhost:3000' has been blocked by CORS policy

Using ExpressJs and ClaudiaJs I have published a web server to AWS Lambda. This server's job is to process Stripe payments. I am trying to get my React SPA to submit the Stripe checkout from the client, but am receiving a CORS error when I try to submit.

How can I avoid this CORS error? I would imagine I need to either publish both client and AWS server on the same TLD (not sure how to make that work), or I'd need to disable CORS on the server (but that seems insecure).

Stripe server call:

    this.handler = StripeCheckout.configure({
        key: test_key,
        locale: "auto",
        mode: "no-cors",
        name: "Company 1234",
        description: "donation",
        token: token => {
            // Send the donation to your server
            console.log("server pinged");

            fetch(`${backendUrl}/charge`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    stripeToken: token,
                    chargeAmount: this.state.donationAmount
                })
            })
                .then(res => res.json())
                .then(json => {
                    console.log("response is " + json);
                    this.setState({ donationResponse: "Thank you for donating!" });
                })
                .catch(error => {
                    this.setState({
                        donationResponse:
                            "There was an issue processing your request. Please try again later"
                    });
                });
        }
    });

Form submission

formSubmit = async event => {
    console.log("form submitted");
    event.preventDefault();

    const amount = this.state.donationAmount * 100; // Needs to be an integer in cents
    this.handler.open({
        amount: Math.round(amount)
    });
};

1 answer

  • answered 2018-11-08 07:38 Sangam Belose

    You can pass origin header in request from your local app. And in response from AWS lambda you can add below response headers :

    headers :{
        "access-control-allow-origin": "localhost",
        "access-control-allow-credentials": "true"
    }
    

    In lambda environment variables, you can configure list of allowed origin separated by comma(,) to ensure only legitimate domain are getting access. something like below:

     "localhost, yourdomain.com"
    

    The CORS issue is really around browser blocking request for other domain, which can be solved by adding above headers.

    I also have faced similar issue, where we had request routed through apigateway -- lambda.