簡體   English   中英

使用 dio 在發布請求中出現顫振錯誤 403

[英]flutter error 403 in post request using dio

我有仇恨問題。 我正在嘗試使用 dio 登錄,登錄方法運行良好,但是當我輸入無效憑據時,dio 給了我這個錯誤:

錯誤

執行錯誤

我創建了一個布爾函數,如果狀態碼為 200,它將返回 true 或 false,否則它將返回 true,否則將返回 false,但是當使用正確的憑據登錄時,一切正常,一切都按原樣進行,但是登錄時使用無效憑據,上述錯誤會導致此錯誤。 我使用共享首選項將令牌存儲在應用程序中,邏輯很簡單,如果是 200,我將登錄應用程序,否則它會顯示我在另一個文件中制作的小吃店,這是我的代碼:

loginFinal() async {
    if (formKey.currentState!.validate()) {
      bool loginIsOk = await loginConect();
      if (loginIsOk) {
        Get.offAllNamed("/home");
        await Future.delayed(const Duration(seconds: 1));
        message(MessageModel.info(
          title: "Sucesso",
          message: "Seja bem vindo(a) influenciador(a)",
        ));
      } else {
        loaderRx(false); //LOADER
        message(MessageModel.error(
          title: "Erro",
          message: "Erro ao realizar login",
        ));
      }
    }
  }

  //LOGICA DE ENTRAR NO APP

  Future<bool> loginConect() async {
    final dio = Dio();
    String baseUrl = "https://soller-api-staging.herokuapp.com";

    loaderRx(true); //LOADER

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    final response = await dio.post(
      baseUrl + "/auth",
      data: jsonEncode(
        {
          "login": emailController.text,
          "senha": passWordController.text,
        },
      ),
      options: Options(
        headers: {'Content-Type': 'application/json; charset=UTF-8'},
        method: "post",
      ),
    );
    if (response.statusCode == 200) {
      await sharedPreferences.setString(
        "token",
        "string: ${response.data["string"]}",
      );
      print("Resposta: ${response.data["string"]}");

      loaderRx(false);

      return true;
    } else {
      print("RESPOSTA: ${response.data}");

      return false;
    }
    
  }
}

如果頭中的狀態代碼不是 200,Dio 總是拋出異常,您將需要使用 try catch 捕獲異常。

在 catch 方法中,您可以檢查錯誤的類型是否為DioError ,然后處理該異常,

這是我在代碼中用於處理此行為的登錄過程的代碼片段。

Future<SignInApiResponse> signInUser(String _email,String _password) async {
try {
  final dio = Dio(ApiConstants.headers());
  final Response response = await dio.post(
    ApiConstants.baseUrl + ApiConstants.signInUrl,
    data: {"email": _email,
"password": _password,
    },
      );
      if (response.statusCode == 200) {
        return SignInApiResponse.fromJson(response.data);
      } else {
        return SignInApiResponse(message: response.toString());
      }
    } catch (e) {
      if (e is DioError) {
        if (e.response?.data == null) {
          return SignInApiResponse(message: Messages.loginFailed);
        }
        return SignInApiResponse.fromJson(e.response?.data);
      } else {
        return SignInApiResponse(message: e.toString());
      }
    }
  }

希望這會有所幫助,如果不是,您可以始終使用在類似情況下不會引發異常的http 包

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM