【问题标题】:How to call GET method with URL and take HTML response in Flutter web如何在 Flutter web 中使用 URL 调用 GET 方法并获取 HTML 响应
【发布时间】:2021-03-28 00:30:21
【问题描述】:

我的任务是通过 GET 方法使用颤振调用 web 中的链接,并获取将来我想在我所在的同一页面上显示的 html。

这是一个例子:

final response = await http.get('SOME URL',
    headers: {'Access-Control-Allow-Origin': '*'});

if (response.statusCode == 200) {
  print("200: Try to get HTML");
  // TODO get HTML from response
  return jsonDecode(response.body).toString();
} else {
  // If the server did not return a 200 OK response,
  // then throw an exception.
  throw Exception('Failed to load album');
}

问题是当我初始化页面时,我调用了这个链接,但是浏览器阻塞并且不允许调用

错误示例:

Access to XMLHttpRequest at 'URL' from origin 'http://localhost:55827' 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.

据我所知,问题是我在本地主机上调用了其他链接,因此 CORS 阻塞。

我找不到解决此问题的方法。请帮助我,在初始化期间,我可以使用 url 调用 GET 方法并从响应中获取 html 吗?

【问题讨论】:

    标签: flutter get cors flutter-web


    【解决方案1】:

    您需要在您使用的后端页面中允许跨源请求,而不是在 http 标头中。命令是否不同取决于您使用的语言,即后端使用的 php、node js、python 等。

    如果您使用的是 PHP,那么您必须指定此标头 -

    header('Access-Control-Allow-Origin: *');

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      相关资源
      最近更新 更多