简体   繁体   English

XMLHttpRequest 到 API GATEWAY 不起作用

[英]XMLHttpRequest to API GATEWAY not working

I was trying to make a call to API Gateway to display the JSON returned by it using XMLHttpRequest .My web page is hosted on AWS S3.我试图调用 API Gateway 以显示它使用 XMLHttpRequest 返回的 JSON。我的网页托管在 AWS S3 上。 When I tried I got the following Error-当我尝试时,出现以下错误-

Failed to load {url of API} : Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.无法加载 {url of API}:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Access-Control-Allow-Origin。

The code for the Request is -请求的代码是 -

var config = {
            headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Allow-Methods": "DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT",
            "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token"
            }
            } 

            axios.get(API_URL,config)
            .then(function (response) {
                    console.log(response);
            })

My CORS setup in amazon s3 is我在亚马逊 s3 中的 CORS 设置是

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>https://s3.ap-south-1.amazonaws.com</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Details - Webpage Hosted on AWS S3 Sending a Request to AWS API gateway详细信息 - 托管在 AWS S3 上的网页向 AWS API 网关发送请求

Background -背景 -
Checked this this and this on stackoverflow but it could not help me solve the problem.在stackoverflow上检查了thisthis ,但它无法帮助我解决问题。

EDIT:编辑:

As stated I tried removing the config from axios call.如前所述,我尝试从 axios 调用中删除配置。 I got a ERROR as我得到了一个错误

No 'Access-Control-Allow-Origin' header is present on the requested resource.请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin ' https://s3.ap-south-1.amazonaws.com ' is therefore not allowed access.因此,不允许访问来源“ https://s3.ap-south-1.amazonaws.com ”。

This method worked for me这个方法对我有用

The code I used :-我使用的代码:-

        axios.get(API_URL)
        .then(function (response) {
                console.log(response);
        })

CDN for AXIOS - AXIOS 的 CDN -
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

Then I had to enable the response headers in API GATEWAY which I was missing.然后我必须在 API GATEWAY 中启用我缺少的响应头
It can be done using steps mentioned here or on Official AWS Website as mentioned by @Michael-sqlbot in comments.可以使用此处提到的步骤或@Michael-sqlbot 在评论中提到的官方 AWS 网站上的步骤来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM