본문 바로가기
삽질하는 개발자 hashblown

프론트엔드 개발자의 TIL #001

by hashblown 2019. 11. 2.

TIL #001

191102 토

 


오늘 배운 점

<Flutter>

1. 서버에 Cookie를 업데이트하여 사용자 세션 유지 목적으로 주고받기

  • http request시 헤더를 활용하기 시작
class Cookie{
  static String rawCookie = '0';
  static void updateCookie(http.BaseResponse response) {
    rawCookie = response.headers['set-cookie'];
    if (rawCookie != null) {
      int index = rawCookie.indexOf(';');
      headers['cookie'] =
      (index == -1) ? rawCookie : rawCookie.substring(0, index);
    }
    print('cookie: $rawCookie');
  }
}
  • 쿠키 관련 클래스와 전역 변수를 만들어주었다.
  • 처음에 response를 받아올때 http.Response로 했더니 이미지 업로드시 사용하는 http.MultipartRequest에서는 쿠키값을 이용할 수 없었다. http.ByteStream을 포함한 response들을 처리하기 위해 http.BaseResponse를 사용해주었더니 해결됐다.
  •  get이나 post 등에서 쿠키를 보낼 때는 아래와 같이 쿠키 정보를 넣어주면 된다.
Future<Data> _fetchData() async {
    final res = await http.post(url, headers: {HttpHeaders.cookieHeader: Cookie.rawCookie}, 
    		body: {'page': PostParam.page.toString(), 'lastDate': PostParam.lastDate});
    final jsonData = json.decode(res.body);
    print('jsonData: $jsonData');
    return Data.fromJson(jsonData);
  }

2. 사용자 세션 유지로 구현할 수 있는 다양한 SNS 기능 실습

  • 팔로우/언팔로우 기능 - 특정 타 유저와의 관계 status를 받아와서 팔로잉 버튼 클릭에 따라 팔로우/언팔로우 상태 변경 및 화면 새로고침을 통한 반영
 void follow(int i) async {
    //팔로잉 대상 아이디
    final id = UserParam.allUsers[i]._id;
    String followUrl = UserParam.url2;
    followUrl += id;
    final res = await http.get(followUrl, headers: {HttpHeaders.cookieHeader: Cookie.rawCookie});
    final jsonData = json.decode(res.body);
    print('jsonData: $jsonData');
    //follow값 바꾸기
    UserParam.allUsers[i].isStatus = jsonData['status'];
    setState(() {
      buildList();
    });
  }
  
  followButton(int i) {
    if (UserParam.allUsers[i].isStatus == 1) {
      return FlatButton(
        onPressed: () {
          follow(i);
        },
        child: Text('언팔로우', style: TextStyle(color: Colors.grey, fontSize: 18, fontFamily: 'Noto_Bold'),),
      );
    } else return FlatButton(
      onPressed: () {
        follow(i);
      },
      child: Text('팔로우', style: TextStyle(color: Colors.red, fontSize: 18, fontFamily: 'Noto_Bold'),),
    );
  }

  
  •  게시글 공감 기능 - 팔로잉 버튼을 응용하여 기존 게시물 정보에 사용자의 공감 버튼 클릭에 따라 좋아요 아이콘 및 공감수 변경
void like(int i) async {
    final id = PostParam.allPosts[i]._id;
    String likeUrl = Cookie.serverUrl + '/flipLike/post/' + id + '/0';
    final res = await http.get(likeUrl, headers: {HttpHeaders.cookieHeader: Cookie.rawCookie});
    final jsonData = json.decode(res.body);
    print('jsonData: $jsonData');
    //like 상태 바꾸기
    PostParam.allPosts[i].likeStatus = jsonData['status'];
    //like 숫자 바꾸기
    PostParam.allPosts[i].like_count = jsonData['likeNum'];
    setState(() {
      buildList();
    });
  }
  
  
  • 게시물의 댓글 조회 기능 - 게시물의 식별자를 받아와서 해당 게시물의 자식으로 있는 댓글목록 불러오기
OutlineButton(
   borderSide: BorderSide(color: Colors.red),
   textColor: Colors.red,
   shape: RoundedRectangleBorder(
   		borderRadius: BorderRadius.circular(30.0)),
        child: Text('댓글 조회',
           style: TextStyle(fontSize: 18, fontFamily: 'Noto_Bold'),),
           onPressed: () {
               Navigator.pushNamed(context, '/comment');
               PostParam.postId = PostParam.allPosts[i]._id;
           }
),

class MentParam {
  static int page = 1;
  static String lastDate = '0';
  static bool scrollFlag = false;
  static List<MentOne> allMents = [];
}

//테스트 파일 관련 클래스 시작
class Comment extends StatefulWidget {
  @override
  _CommentState createState() => _CommentState();
}


내일 배울 것

<Flutter>

1. 소셜로그인을 통해 세션 유지하기 - 쿠키 대신 
2. 프로필 정보 수정
3. 텍스트 에디터를 통한 게시글 작성

 


더보기

- 백엔드와의 협업은 역시 끊임없는 소통이다.
- 마케팅 전략을고민하는 것도 꽤 막막하다.
- 코딩은 하다보면 실마리를 찾게 되고, 끝까지 따라가는 재미가 있다!
- 에러도 많이 겪어봐야 잘 해결할 수 있다.

댓글