为什么我的 flutter app http post 请求只能在本地主机上工作

Why my flutter app http post request only work in localhost

我正在制作一个具有登录功能的应用程序。它在我的本地主机上向 API 调用 HTTP POST 请求以检查用户名和密码的有效性,如果它与 PhpMyAdmin 上的数据匹配,那么它将路由到会员页面。

但是,我想在我的主机上将 await http.post 从 localhost XAMPP link 更改为 public API link .但是每当我这样做时它都会抛出一些错误,当我点击登录按钮时什么也没有发生。这是代码:

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController user = new TextEditingController();
  TextEditingController pass = new TextEditingController();

  String msg = '';

  Future<List> _login() async {
    final response =
        await http.post("http://tunnamacbook.local/login.php", body: {
      "username": user.text,
      "password": pass.text,
    });

    var datauser = json.decode(response.body);

    if (datauser.length == 0) {
      setState(() {
        msg = "Đăng nhập thất bại";
      });
    } else {
      if (datauser[0]['level'] == 'admin') {
        Navigator.pushReplacementNamed(context, '/AdminPage');
      } else if (datauser[0]['level'] == 'member') {
        Navigator.pushReplacementNamed(context, '/MemberPage');
      }

      setState(() {
        username2 = datauser[0]['name'];
      });
    }

    return datauser;
  }

...there's more but it's unnecessary to show here...

错误如下:

[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: FormatException: Unexpected end of input (at character 1)
^
#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
#1      _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:523:7)
#2      _parseJson (dart:convert-patch/convert_patch.dart:41:10)
#3      JsonDecoder.convert (dart:convert/json.dart:506:36)

错误是下面的蓝线:

我想通了。这是 CORS 政策的问题。在每个 http API 调用中设置 CORS 允许 header 修复它。对于那些想要此问题的示例代码的人,请在 Google 上搜索 CORS allow header for Flutter http call。由于我将我的移动应用程序编程框架切换到 React Native 以获得更好的支持和更大的 Whosebug 社区,所以我不能再在 Flutter 中为这个问题编写代码了。