【问题标题】:Access to fetch at $AWS_LAMBDA_SITE from origin 'http://localhost:3000' has been blocked by CORS policyCORS 策略已阻止从源“http://localhost:3000”获取 $AWS_LAMBDA_SITE 的访问权限
【发布时间】:2019-04-11 16:23:50
【问题描述】:

使用 ExpressJs 和 ClaudiaJs 我已将 Web 服务器发布到 AWS Lambda。该服务器的工作是处理 Stripe 付款。我正在尝试让我的 React SPA 从客户端提交 Stripe 结帐,但是当我尝试提交时收到 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)
    });
};

【问题讨论】:

    标签: amazon-web-services cors aws-lambda single-page-application


    【解决方案1】:

    您可以在本地应用的请求中传递原始标头。作为来自 AWS lambda 的响应,您可以添加以下响应标头:

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

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

     "localhost, yourdomain.com"
    

    CORS 问题实际上是围绕浏览器阻止其他域的请求,可以通过添加上述标头来解决。

    我也遇到过类似的问题,我们通过 apigateway -- lambda 路由请求。

    【讨论】:

    • 这是一个很大的帮助。我已将mode: "no-cors" 添加到我的获取请求中,并将var cors = require("cors");app.use(cors()); app.options("*", cors()); // include before other routes 添加到我在expressjs 中的服务器初始化中。错误消失,服务器可以响应。但是,现在我的请求正文是空的。不管我做什么,它都是空的,知道那可能是什么吗?仅供参考,我也通过app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));使用body-parser
    • 问题在这里解决了 - stackoverflow.com/questions/53214229/…
    猜你喜欢
    • 2020-07-29
    • 2021-03-08
    • 2021-01-24
    • 2021-07-03
    • 1970-01-01
    • 2021-10-05
    • 2020-09-01
    • 2021-01-23
    • 2020-12-27
    相关资源
    最近更新 更多