使用http POST颤动Web时出现XMLHttpRequest错误 [英] XMLHttpRequest error while using http post flutter web

查看:0
本文介绍了使用http POST颤动Web时出现XMLHttpRequest错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对我的API-AWS API网关进行HTTP POST调用时遇到此错误XMLHttpRequest error.。我当前的流程是Ffltter Web->;API网关->;lambda->;rds。

我知道已经有几个与此like相关的问题,但正如其中一个答案所建议的那样,添加一些头来响应lambda。但这对我不起作用。

在做了一些调查后,我发现问题与CORS有关。现在,禁用Chrome中的CORS是一个临时修复程序,建议在本question中使用。

我研究后发现的其他一些解决方案建议在我的API和前端部分启用CORS,我已经添加了Header,但都不起作用。

fetchData() async {
    String url =
        "myUrl";
    Map<String, String> headers = {
      "Access-Control-Allow-Origin": "*", // Required for CORS support to work
    };
    String json = '{"emailId":"emailId"}';
    http.Response response =
        await http.post(Uri.parse(url), headers: headers, body: json);
    print(response.body);
    return response.body;
  }

解决此问题的正确方法是什么?

推荐答案

我已经解决了我的问题,不打算删除此问题,因为没有很多明确定义的解决方案来解决此问题。 适用于使用Ffltter Web和AWS API-Gateway的未来观众。

  1. 如果您遇到这个问题,说明它是从后端而不是从颤动端
  2. XMLHttpRequest错误。是由CORS引起的

API-Gateway开启CORS问题的解决方案如下link

但是,如果您使用的是与lambda和api-ateway的代理集成,那么在这种情况下,启用CORS将无济于事,您必须从lambda函数的响应传递标头。如

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)
};

格式需要相同。此外,一个特别的问题对我理解整个问题有很大帮助,那就是了解问题link的各种答案。

现在我的问题来了,我做错了什么,我从前端传递了 "Access-Control-Allow-Origin": "*",,并且在API网关中启用CORS也发送了类似的标头,这给我带来了问题

Access to XMLHttpRequest at 'API-URL' from origin 'http://localhost:63773' 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 particular line

因此,将我的函数更改为此函数后,一切工作正常

fetchData() async {
    String url =
        "API-url";
    Map<String, String> headers = {
      "Content-Type": "text/plain",
    };
    String json = '{"emailId":"emailId"}';
    Map<String, String> map = Map();
    map["emailId"] = "sahaj@rootsapp.in";
    http.Response response = await http
        .post(Uri.parse(url), headers: headers, body: jsonEncode(map))
        .then((value) {
      print("onThen> " + value.body.toString());
    }).onError((error, stackTrace) {
      print("onError> " +
          error.toString() +
          " stackTrace> " +
          stackTrace.toString());
    });
  }

这篇关于使用http POST颤动Web时出现XMLHttpRequest错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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