【问题标题】:After posting backend responding a token . Now how will get that that token? flutter http request发布后端响应令牌后。现在将如何获得那个令牌?颤振http请求
【发布时间】:2022-01-06 15:26:30
【问题描述】:

登录后端响应令牌后。现在如何获得那个令牌?

我在这个项目中使用了 HTTP 包。我是新来的。我的代码示例:

  Future<void> login() async {
if (_password.text.isNotEmpty && _number.text.isNotEmpty) {
  final response = await http.post(
    Uri.parse(
        'https://api.azabazar.com/api/login/?fbclid=IwAR2Sz4ky31HCG4g2Sbhn08LV3QqV76YEaIIQwpRavXRB1A4o0fq4aiQ22kE'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
      HttpHeaders.authorizationHeader: 'Basic your_api_token_here', //here i want my token
    },
    body: jsonEncode(<String, String>{
      "username": _number.text,
      "password": _password.text,
    }),
  );
  if (response.statusCode == 201) {
    const Text("Loged in");
  } else {
    throw Exception('Failed to find account.');
  }
} else {
  ScaffoldMessenger.of(context)
      .showSnackBar(const SnackBar(content: Text("invalid form")));
}

}

【问题讨论】:

    标签: flutter http dart http-post flutter-http


    【解决方案1】:

    我假设你从服务器得到了类似的东西:

    {
      "data": {
        "token": "TOKEN"
        ...
      }
    }
    

    你可以像这样获取令牌:

    if (response.statusCode == 201) {
      final decodedResponse = jsonDecode(response.body) as Map;
      final token = decodedResponse['data']['token'];
    } else {
      throw Exception('Failed to find account.');
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2022-06-27
    • 2021-03-03
    • 2020-01-24
    • 2022-08-23
    相关资源
    最近更新 更多