inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[코드팩토리] [중급] Flutter 진짜 실전! 상태관리, 캐시관리, Code Generation, GoRouter, 인증로직 등 중수가 되기 위한 필수 스킬들!

dio 패키지는 redirect 처리를 하기 어렵나요?

868

바코드

작성한 질문수 3

0

Node.js express 로 라우터를 설정해 다음과 같은 코드로 http 통신을 했습니다

/api/test1 주소의 post 라우터에서 /api/test2 주소의 post 라우터로 redirect 되는 통신을 테스트 해보았습니다

                onPressed: () async {
                  var res = await http.post(Uri.parse("$uri/api/test1"),
                      headers: <String, String>{
                        'Content-Type': 'application/json; charset=UTF-8',
                      },
                      body: jsonEncode(
                        {
                          "key1": "1000",
                        },
                      ));
                  if (res.statusCode == 307) {
                    var newURL = res.headers["location"];
                    print(res.body);
                    res = await http.post(Uri.parse("$uri$newURL"),
                        headers: <String, String>{
                          'Content-Type': 'application/json; charset=UTF-8',
                        },
                        body: jsonEncode(
                          {
                            "key1": "1000",
                          },
                        ));
                    print(res.body);
                  } else {
                    var data = res.body;
                    print(data);
                  }
                },

테스트 결과 제가 데이터를 올바르게 전송할 수 있었습니다 그리고 이번에 선생님의 강의를 듣고 dio라는 패키지를 알게되어서 dio 패키지를 통해서 똑같은 통신 테스트를 해 보았습니다

                onPressed: () async {
                  final dio = Dio(BaseOptions(
                    contentType: "application/json",
                    followRedirects: false,
                    maxRedirects: 5,
                  ));

                  final url = "$uri/api/test1";
                  final body = {'key1': '1000'};
                  final headers = {'Content-Type': 'application/json'};

                  try {
                    Response res = await dio.post(
                      url,
                      data: body,
                    );
                    if (res.statusCode == 307) {
                      final redirectUrl = res.headers.value("location");
                      final redirectRes = await dio.post(
                        redirectUrl!,
                        data: body,
                        options: Options(
                          headers: headers,
                          method: "POST",
                        ),
                      );
                      print(redirectRes.data);
                    } else {
                      final data = res.data;
                      print(data);
                    }
                  } catch (e) {
                    print("error 발생 $e");
                  }
                },

followRedirects 을 true 로 해도 307 코드를 해결하지는 못하는것 같습니다

flutter: error 발생 DioError [DioErrorType.response]: Http status error [307]

어떻게 dio 패키지로 redirect 를 처리 할 수 있을까요?

flutter 하이브리드-앱

답변 1

0

코드팩토리

안녕하세요!

아무래도 catch문에서 처리하셔야 할 것 같습니다.

Dio에서 307의경우 에러로 인식하는 것 같네요.

감사합니다!

Isar 마지막 업데이트는 2년전입니다.

0

31

0

FlutterSecureStorage 질문

0

32

0

Dio onError Interceptor 만드는 부분에 질문이 있습니다.

0

80

2

관리자 기능에 대한 질문

0

100

2

part 'restaurant_model.g.dart';

0

92

1

36강. dio 인터셉터에 storage를 전달하는 코드가 이해 안되는데요. 도움 부탁드립니다.

0

56

2

2번 반환 상황 관련 질문

0

61

2

riverpod 3.0

0

140

2

Asset folder??

0

83

2

디자이너와 협업 시 프레임 크기 설정 관련 질문

0

114

2

FutureProvider, StateNotifierProvider 선택 기준

0

70

2

컴포넌트 모델화

0

64

2

쿼리 파라미터

0

84

2

화면 안보임

0

68

2

PaginationListView

0

54

1

강의중 37.Dio onErrorInterceptor 작업하기 dio 관련 질문입니다.

0

103

2

프로토타입이미지

0

62

2

여러 객체를 상태 관리하는 방법에 대한 질문

0

85

2

장바구니 결제하기 응답이 500이 옵니다.

0

105

2

removeFromBasket에서 await patchBasket()을 마지막에 하면 에러나는거 아닌가요?

0

67

2

이 두가지는 완전히 동일한 기능인가요?

0

106

3

내부 코드를 작성하지 않은 CursorPaginationLoading가 어떻게 로딩상태를 갖는지 잘 모르겠습니다...

0

77

2

_SplashScreenState에서 storage를 late로 호출해서 한번만 불러와도 되나요?

0

86

2

코딩 작성 순서 관련 질문

0

88

2