XMLHttpRequest error in flutter web [Enabling CORS AWS API gateway]

半城伤御伤魂 提交于 2020-12-30 06:58:06

问题


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 ?


回答1:


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",
  "Access-Control-Allow-Methods": "POST, OPTIONS"
},
    body: JSON.stringify(item)
};


来源:https://stackoverflow.com/questions/60191683/xmlhttprequest-error-in-flutter-web-enabling-cors-aws-api-gateway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!