javascript - 收到错误来源 'null' 已被 CORS 策略阻止?

标签 javascript jquery amazon-web-services cors aws-api-gateway

我使用以下代码调用 AWS API 网关。

<!DOCTYPE html>
<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#btn").click(function(){
                var finalJson = {
                  "entityType": "abc",
                  "entityId": "123"
                };
                $.ajax({
                    type : "POST",
                    contentType : "application/json",
                    xApiKey : "api-key"
                    url : "api-gateway-url",
                    data : JSON.stringify(finalJson),
                    dataType : 'json',
                    timeout : 100000,
                    success : function(data){
                        alert('Congrats! You got the response');
                        console.log(data);
                    },
                    error : function(data){
                        alert('Error');
                        console.log(data);
                    }
                });
            });
        });
    </script>
    </head>
    <body>
        <h2>API Gateway call</h2>
        <button type="button" id="btn">Request data</button>
        <p id="demo"></p>
    </body>
</html>

API Gateway 有一个 POST 方法,它与 Lambda 函数链接。 我已经在 API gatewaye 中启用了 CORS。 单击“请求数据”按钮后,显示以下错误。

Access to XMLHttpRequest at 'API Gateway URL' from origin 'null' 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.

请帮忙,谢谢:)

最佳答案

我认为这个问题与 this 有关,而不是因为 API 网关。如果您使用 * 配置了 CORS 配置,您应该能够直接从前端调用。

关于javascript - 收到错误来源 'null' 已被 CORS 策略阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69956920/

相关文章:

javascript - Node.js:socket.io 关闭客户端连接

javascript - 提交后在 php 中添加文本行

javascript - 满足所有条件后隐藏工具提示弹出窗口

jquery - Bootstrap Navbar Hamburger 在折叠时不起作用

javascript - 使用 ajax Jquery 和 asp.net 重定向具有值的页面

javascript - 如何从非组件辅助函数访问 redux 的商店?

javascript - RAILS/Ruby 错误 "CALL_AND_RETRY_0: Allocation failed - process out of memory"

amazon-web-services - 单独使用 AWS S3 或 S3 和 Cloudfront 进行视频下载

amazon-web-services - 如何为运行 COUCHBASE 2.1.1 社区 AMI 的 EC2 实例添加主机名?

javascript - 在 Angular 中将 JSON 格式字符串转换为真实对象