dart 当我在Flutter Emulator中打开我的应用程序时,Flutter应用程序中的令牌已过期

mefy6pfw  于 2023-11-14  发布在  Flutter
关注(0)|答案(1)|浏览(116)

我是开发Flutter应用程序的新手。每当我在Flutter模拟器中打开应用程序时,我的应用程序都会显示“Expired Token”消息。我可以修改代码的哪一部分来刷新我的令牌?我不知道这是否是为了让你帮助我而提供的正确文件,但我只是把它放在这里。

import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart';
import 'package:http/http.dart' as http;
import 'package:nb_utils/nb_utils.dart';
import 'package:plant_flutter/network/RestApi.dart';
import 'package:plant_flutter/utils/common.dart';
import 'package:plant_flutter/utils/constants.dart';

import '../main.dart';

Map<String, String> buildHeaderTokens({bool print = true}) {
  Map<String, String> header = {
    HttpHeaders.contentTypeHeader: 'application/json; charset=utf-8',
    HttpHeaders.cacheControlHeader: 'no-cache',
    HttpHeaders.acceptHeader: 'application/json; charset=utf-8',
  };

  if (userStore.isLoggedIn) {
    header.putIfAbsent(HttpHeaders.authorizationHeader, () => 'Bearer ${userStore.token}');
  }
  if (print) log(jsonEncode(header));
  return header;
}

Uri buildBaseUrl(String endPoint) {
  Uri url = Uri.parse(endPoint);

  if (!endPoint.startsWith('https')) url = Uri.parse('$mDomainUrl$endPoint');

  log('URL: ${url.toString()}');

  return url;
}

Future<Response> buildHttpResponse(String endPoint, {HttpMethod method = HttpMethod.GET, Map? request}) async {
  if (await isNetworkAvailable()) {
    var headers = buildHeaderTokens();
    Uri url = buildBaseUrl(endPoint);

    Response response;

    if (method == HttpMethod.POST) {
      log('Request: ${jsonEncode(request)}');

      response = await http.post(url, body: jsonEncode(request), headers: headers);
    } else if (method == HttpMethod.DELETE) {
      response = await delete(url, headers: headers);
    } else if (method == HttpMethod.PUT) {
      response = await put(url, body: jsonEncode(request), headers: headers);
    } else {
      response = await get(url, headers: headers);
    }

    log('Response ($method): ${response.statusCode} ${response.body.trim()}');
    return response;
  } else {
    throw errorInternetNotAvailable;
  }
}

Future handleResponse(Response response, [bool? avoidTokenError]) async {
  if (!await isNetworkAvailable()) {
    throw errorInternetNotAvailable;
  }

  if (response.statusCode == 401) {
    if (userStore.isLoggedIn) {
      Map<String, dynamic> req = {
        'username': userStore.userEmail,
        'password': userStore.userPassword,
      };

      await authApi.logInApi(req).then((value) {
        throw 'Please try again.';
      }).catchError((e) {
        throw TokenException(e);
      });
    } else {
      throw '';
    }
  }

  if (response.statusCode.isSuccessful()) {
    return jsonDecode(response.body);
  } else {
    try {
      var body = jsonDecode(response.body);
    //  throw errorSomethingWentWrong;
      throw parseHtmlString(body['message']);
    } on Exception catch (e) {
      log(e);
      throw errorSomethingWentWrong;
    }
  }
}

//region Common
enum HttpMethod { GET, POST, DELETE, PUT }

class TokenException implements Exception {
  final String message;

  const TokenException([this.message = ""]);

  String toString() => "Token Exception: $message";
}
//endregion

字符串
谢谢你,我希望你能帮助我。
我没有尝试任何东西,因为我担心我会破坏代码。

y0u0uwnf

y0u0uwnf1#

Expired Token消息表示用于向您的服务器发出请求的认证令牌已过期。要刷新令牌,您需要在Flutter应用中实现令牌刷新机制。

相关问题