代码之家  ›  专栏  ›  技术社区  ›  James L.

在$AWS\u LAMBDA\u站点从源站获取http://localhost:3000'已被CORS策略阻止

  •  1
  • James L.  · 技术社区  · 6 年前

    我使用ExpressJs和ClaudiaJs向AWS Lambda发布了一个web服务器。此服务器的任务是处理条带支付。我试图让我的React SPA提交客户的条带签出,但在我尝试提交时收到CORS错误。

    我怎样才能避免这个CORS错误?我可以想象我需要在同一TLD上发布客户机和AWS服务器(不确定如何使其工作),或者需要在服务器上禁用CORS(但这似乎不安全)。

    条带服务器调用:

        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"
                        });
                    });
            }
        });
    

    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 回复  |  直到 6 年前
        1
  •  2
  •   Sangam Belose    6 年前

    您可以从本地应用程序在请求中传递源站标头。在AWS lambda的响应中,您可以添加以下响应头:

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

    在lambda环境变量中,您可以配置由逗号(,)分隔的允许来源列表,以确保只有合法的域可以访问。如下所示:

     "localhost, yourdomain.com"
    

    CORS的问题实际上是浏览器阻塞了对其他域的请求,这可以通过添加上面的头来解决。