[코드팩토리] [중급] Flutter 진짜 실전! 상태관리, 캐시관리, Code Generation, GoRouter, 인증로직 등 중수가 되기 위한 필수 스킬들!
7강 마지막 들으면서 적용하는데 분명 에뮬레이터도 정상동작인데 dio.dart의 onError함수에서 계속 401 auth에러가 발생한다고 표시가 돼서 콘솔로 디버깅을 했습니다. 그런데 마지막 resending하는 부분까지 정상 도달은 하지만 onResponse의 콘솔은 뜨지않고 재시작해서 accessToken을 다시 발급 받았음에도 계속 onError에서 401auth 에러가 발생합니다. 어떤 부분이 문제일까요 [요약] 토큰만료 =>홈 스크린에 데이터 사라짐 => 재시작 => 홈 스크린에 데이터 불러와짐 => 문제발생 데이터는 불러와지는데 디버그 콘솔에 REQ랑 ERROR표시남(401 AUTH 관련 에러) => 재시작 => 동일 에러 무한 [에러 내용] I/flutter ( 4232): [REQ] [GET] http://10.0.2.2:3000/restaurant/ I/flutter ( 4232): [ERROR] [GET] http://10.0.2.2:3000/restaurant/ I/flutter ( 4232): [ERROR] [MESSAGE] This exception was thrown because the response has a status code of 401 and RequestOptions.validateStatus was configured to throw for this status code. I/flutter ( 4232): The status code of 401 has the following meaning: "Client error - the request contains bad syntax or cannot be fulfilled" I/flutter ( 4232): Read more about status codes at https://developer.mozilla.org/en-US/docs/Web/HTTP/Status I/flutter ( 4232): In order to resolve this exception you typically have either to verify and fix your request code or you have to fix the server code. dio.dart import 'package:dio/dio.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:section2/common/const/data.dart'; class CustomInterceptor extends Interceptor { final FlutterSecureStorage storage; CustomInterceptor({ required this.storage, }); /// 1) 요청 보낼 때 /// 요청이 보내질때마다 /// 만약에 요청의 Headers에 accessToken이 true 이면 /// 실제 토큰을 가져와서 기존 accessToken값을 삭제하고 { /// authorization : Beader $토큰} 값을 추가 @override void onRequest( RequestOptions options, RequestInterceptorHandler handler) async { print('[REQ] [${options.method}] ${options.uri}'); if (options.headers['accessToken'] == 'true') { options.headers.remove('accessToken'); final accessToken = await storage.read(key: ACCESS_TOKEN_KEY); options.headers.addAll( {'authorization': 'Bearer $accessToken'}, ); } if (options.headers['refreshToken'] == 'true') { options.headers.remove('refreshToken'); final refreshToken = await storage.read(key: REFRESH_TOKEN_KEY); options.headers.addAll( {'authorization': 'Bearer $refreshToken'}, ); } return super.onRequest(options, handler); } /// 2) 응답 받을 때 @override void onResponse(Response response, ResponseInterceptorHandler handler) { print( '[RES] [${response.requestOptions.method}] ${response.requestOptions.uri}'); super.onResponse(response, handler); } /// 3) 에러 났을 때 @override void onError(DioException err, ErrorInterceptorHandler handler) async { // 401에러 났을 때 (status code) // 토큰을 재발급 받는 시도를하고 토큰이 재발급되면 // 다시 새로운 토큰을 요청한다. print('[ERROR] [${err.requestOptions.method}] ${err.requestOptions.uri}'); print('[ERROR] [MESSAGE] ${err.message}'); // refreshToken이 없는 경우 final refreshToken = await storage.read(key: REFRESH_TOKEN_KEY); if (refreshToken == null) { // 에러 던질때는 handler.reject()사용 return handler.reject(err); } final isStatus401 = err.response?.statusCode == 401; final isPathRefresh = err.requestOptions.path == '/auth/token'; if (isStatus401 && !isPathRefresh) { final dio = Dio(); try { final res = await dio.post( 'http://$ip/auth/token', options: Options( headers: { 'authorization': 'Bearer $refreshToken', }, ), ); final accessToken = res.data['accessToken']; final options = err.requestOptions; //기존 토큰 변경 options.headers.addAll({ 'authorization': 'Bearer $accessToken', }); await storage.write(key: ACCESS_TOKEN_KEY, value: accessToken); // 에러난 요청options에 토큰값을 신규로 변경하여 재전송 final resending = await dio.fetch(options); return handler.resolve(resending); } on DioException catch (e) { return handler.reject(e); } } return handler.reject(err); } }
안녕하세요 강의 너무 잘 보고 있습니다. 너무 이해하기 쉽게 알려주셔서 열심히 듣고 있는데 state부분에 대해 궁금해서 질문을 드립니다. state는 그럼 글자가 변한다거나 어떤한 것이 변경되는것처럼 이런 상태들이 변하게 할때 state를 사용한다라고 이해하고 이럴때 state를 사용하면 되는건가요?
안녕하세요 css를 공부중인데 선택자에 대해 질문이 있습니다 * {color: white}, body {color: white} 이렇게 전체선택자와 body선택자 둘다 글자 색상을 흰색으로 했는데 전체선택자도 모든 태그의 글자색이 흰색이 되고 body도 모든 글자색이 흰색이 되는데 이 두개의 차이점이 헷갈립니다.
안녕하세요 "부트캠프에서 만든 완벽한 프론트엔드 코스" 강의를 구매해서 열심히 듣고 있습니다. 강의소개에서 웹 프론트엔드 부트캠프 부분에 CRUD에 충실한 여행자 게시판 '트립토크'와 숙박상품을 구매할 수 있는 여행플렛폼이라고 나오는데 그렇다면 이 강의에 이 여행 플랫폼을 만드는 내용도 있나요?
"[코드캠프] 부트캠프에서 만든 고농축 프론트엔드 코스강의" 를 수강하고 배포 부분을 이 강의를 수강하고 있는 수강생입니다. 고농축 강의에서 만든 포트폴리오를 aws에서 배포했을때에, CORS 에러가 다음과 같이 나는 문제가 있는데 어떻게 해결해야할까요? 찾아보니 백엔드에서 CORS 를 허용해야하거나 프론트에서 프록시를 사용하라고 되어있는데 어떻게 해결해야할지 모르겠네요
yarn codegen을 입력하면 이런 에러가 뜹니다 Not all operations have an unique name: fetchBoard: success Saved 1 new dependency. info Direct dependencies └─ @graphql-codegen/cli@5.0.4 info All dependencies └─ @graphql-codegen/cli@5.0.4 코드젠은 이렇게 잘 설치가 되었고 package.json 에도 이렇게 추가해 놓았습니다 "codegen": "graphql-codegen --config codegen.ts" PS C:\Users\young\Desktop\frontend\class-example\my-app> yarn codegen yarn run v1.22.22 warning ..\..\..\..\package.json: No license field $ graphql-codegen --config codegen.ts ✔ Parse Configuration ❯ Generate outputs ❯ Generate to ./src/commons/graphql/ ✔ Load GraphQL schemas ✔ Load GraphQL documents ⠏ Generate [client-preset] the following anonymous operation is skipped: mutation { createBoard(writer: "윰", title: "작성중", contents: "내용작성중") { _id number message } } [client-preset] the following anonymous operation is skipped: query { fetchBoard(number: 1) { number writer title contents } } [client-preset] the following anonymous operation is skipped: query { fetchBoard(number: 2) { number writer title contents } } [client-preset] the following anonymous operation is skipped: query { fetchBoards { number writer title contents } } [client-preset] the following anonymous operation is skipped: query { fetchBoards { number ✔ Parse Configuration ⚠ Generate outputs ❯ Generate to ./src/commons/graphql/ ✔ Load GraphQL schemas ✔ Load GraphQL documents ✖ Not all operations have an unique name: fetchBoard: * fetchBoard found in: - C:/Users/young/Desktop/frontend/class-examp… error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[코드팩토리] [중급] Flutter 진짜 실전! 상태관리, 캐시관리, Code Generation, GoRouter, 인증로직 등 중수가 되기 위한 필수 스킬들!
알림 메세지가 필요해서 firebase 연동을 하던 중에 * What went wrong: Plugin [id: ' com.google.gms.google -services'] was not found in any of the following sources: - Gradle Core Plugins (plugin is not in 'org.gradle' namespace) - Included Builds (No included builds contain this plugin) - Plugin Repositories (plugin dependency must include a version number for this source) 로 빌드가 안되는데 해결책을 봐도 어떻게 풀어가야할지 모르겠습니다. 해결할 수 있는 도움 말씀 주시면 힘이 날 것 같습니다. 감사합니다.
[코드팩토리] [중급] Flutter 진짜 실전! 상태관리, 캐시관리, Code Generation, GoRouter, 인증로직 등 중수가 되기 위한 필수 스킬들!
코드팩토리 디스코드에 질문하면 더욱 빠르게 질문을 받아 볼 수 있습니다! [코드팩토리 디스코드] https://bit.ly/3HzRzUM - 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. repository.g.dart파일을 제너레이션 하면 이렇게 parseErrorLogger? 인스턴스가 자동생성됩니다. 오류도 발생합니다. parseErrorLogger가 있는 부분을 주석처리하고 실행하면 오류가 발생하지 않지만, 빌드시마다 주석이 사라지고 오류가 반복되고있습니다. 코드팩토리님께서 작성하신 코드를 까봐도 해당 코드를 찾을수가 없는것같습니다.