Post命令在终端中工作,但在javascript命令中不起作用

时间:2017-11-16 04:30:21

标签: javascript amazon-web-services curl aws-lambda aws-api-gateway

当我通过终端中的curl运行此帖子时。我的测试功能很棒。我看到我在测试lambda函数内的响应中作为参数传递的名称。但不幸的是,让它通过终端工作不是我的最终目标。

    curl -v -X POST 'https://miyyxihee3.execute-api.us-east-1.amazonaws.com/prod/EchoTest' -H 'content-type: application/json' -d '{
"callerName": "Name!"
}'

我想调用此网址并通过javascript发布数据。我的问题是当我尝试在javascript上进行POST调用时,我收到了与CORS相关的错误。更具体地说,错误是: Failed to load https://miyyxihee3.execute-api.us-east-1.amazonaws.com/prod/EchoTest: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

以下是我在javascript代码中尝试过的内容:

 var xmlhttp = new XMLHttpRequest();   
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {
        alert(xmlhttp.responseText);
    }
}
xmlhttp.open("POST", "https://miyyxihee3.execute-api.us-east-1.amazonaws.com/prod/EchoTest");
xmlhttp.setRequestHeader('Access-Control-Allow-Methods', 'POST');
xmlhttp.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token');
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({callerName:"Name!"}));

P.S。我是javascript的新手。我在一些CORS文档中一直在讨论。根据我的理解,CORS需要特定的标题来容纳帖子请求?我在AWS API网关中启用了CORS。有点困惑为什么它在终端工作但不在javascript中。有人可以帮忙吗?

0 个答案:

没有答案