抖动网站中的XMLHttpRequest错误[启用CORS AWS API网关] [英] XMLHttpRequest error in flutter web [Enabling CORS AWS API gateway]

查看:120
本文介绍了抖动网站中的XMLHttpRequest错误[启用CORS AWS API网关]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:事实证明,这与抖动无关,与我将API网关设置为Lambda代理的事实有关

每次尝试出错时,我都试图从Flutter Web应用程序访问API端点,并给我以下错误.

获取传感器数据时出错:DioError [DioErrorType.RESPONSE]:XMLHttpRequest错误.

我知道SO上有几个问题(例如

访问控制允许标题"中的文本是

内容类型,X-Amz日期,授权,X-Api-Key,X-Amz-安全令牌"

在API网关上启用CORS似乎无济于事,当我尝试访问API时,在Flutter Web应用程序上仍然遇到相同的错误.

有趣的是,如果我从chrome中访问API,则该API可以很好地工作(即,将API URL粘贴到浏览器中,然后按Enter).只有当我尝试从Flutter Web应用程序中访问API时,它才会失败.

问题:如何在我的API网关中启用CORS支持,以便我的Flutter Web应用程序可以使用该API?

解决方案

这对我有用,我在lambda函数上添加了以下标头

 返回{statusCode:200,标头:{"Access-Control-Allow-Origin":"*",//对于CORS支持有效"Access-Control-Allow-Credentials":true,//对于Cookie和HTTPS授权标头是必需的"Access-Control-Allow-Headers":来源,内容类型,X-Amz-日期,授权,X-Api-Key,X-Amz-安全性令牌,语言环境",访问控制允许方法":"POST,OPTIONS";},正文:JSON.stringify(item)}; 

Note: It turns out that this had nothing to do with flutter and everything to do with the fact that I had set the API gateway to a Lambda Proxy

I am trying to hit an API endpoint from a Flutter web application, every time it errors out and gives me the following error.

Error getting sensor data: DioError [DioErrorType.RESPONSE]: XMLHttpRequest error.

I know there are several questions here on SO(like this and this) discussing this issue and the solution seems to be to enable CORS support on the server-side. I am using the AWS API gateway to build the API, I followed these instructions to enable CORS support from my API. Here are my CORS setting from the API gateway console.

The text in the "Access-Control-Allow-headers" is

'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'

Enabling CORS on the API gateway didn't seem to help, I am still getting the same error on my flutter web app when I try to hit an API.

The funny thing is, the API work perfectly fine if I hit the API from chrome (i.e. pasting the API URL on the browser and hitting enter). It only fails when I try to hit the API from the flutter web app.

Question: How do I enable CORS support in my API gateway so my flutter web app can use the API ?

解决方案

this worked for me, I added the below header on the lambda function

return {
    statusCode: 200,
     headers: {
  "Access-Control-Allow-Origin": "*", // Required for CORS support to work
  "Access-Control-Allow-Credentials": true, // Required for cookies, authorization headers with HTTPS
  "Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
  "Access-Control-Allow-Methods": "POST, OPTIONS"
},
    body: JSON.stringify(item)
};

这篇关于抖动网站中的XMLHttpRequest错误[启用CORS AWS API网关]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆