ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Modern JavaScript REST API / SPA
    FrontEnd/JavaScript 2023. 3. 4. 15:49

    1. REST (Representational State Transfer)

    •  URI에 정보의 자원 표시  (동사보다 명사 사용), ex. GET /todos/1
    • 자원에 대한 행위는 HTTP Method로 표현 (GET, POST, PUT, DELETE 등)  ex. DELETE / todos/1   

     

    Method Action Role PayLoad
    GET index/retrieve 모든/특정 리소스를 조회 x
    POST create 리소스를 생성
    PUT replace 리소스의 전체를 교체
    PATCH modify 리소스의 일부를 수정
    DELETE delete 모든/특정 리소스를 삭제 x

     


     

    2. REST 구성

    • 자체 표현 구조

     

    구성요소 내용 표현방법
    Resource 자원 HTTP URI
    Verb 자원에 대한 행위 HTTP Method
    Representations 자원에 대한 행위의 내용 HTTP Message Pay Load

     

    //1. GET
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost:5000/todos');
    xhr.send();
    
    //2. POST
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://localhost:5000/todos');
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.send(JSON.stringify({ id: 4, content: 'Angular', completed: true }));
    
    //3. PUT
    const xhr = new XMLHttpRequest();
    xhr.open('PUT', 'http://localhost:5000/todos/4');
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.send(JSON.stringify({ id: 4, content: 'React', completed: false }));
    
    //4. PATCH
    const xhr = new XMLHttpRequest();
    xhr.open('PATCH', 'http://localhost:5000/todos/4');
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.send(JSON.stringify({ completed: true }));
    
    //5. DELETE
    const xhr = new XMLHttpRequest();
    xhr.open('DELETE', 'http://localhost:5000/todos/4');
    xhr.send();

     


    3. SPA (Single Page Application)

    • SPA : 단일 페이지 애플리케이션 패러다임으로 단일페이지 구성으로, 배포가 간단하며 네이티브 앱과 유사한 퍼포먼스를 보여줌
    • 최초 접근시 한번만 정적 리소스를 다운로드하고, 새로운 요청시 갱신에 필요한 데이터만  JSON형식으로 전달받아 갱신
    • 전체적인 트래핑 감소와 네이티브앱과 유사한 사용자 경험제공 (반응성, 속도, 사용성 이점)
    • CSR (Client Side Rendering) : 비동기 모델 기반 (SSR/Server Side Rendering이 아님)
    • History를 관리할 수 없어 SEO 이슈가 존재

     


    4. Routing

    • 출발지점부터 목적지까지의 경로를 결정하는 기능
    • Task 수행시 View에서 다른 View로 화면 전환시 Navigation을 관리하기 위한 기능
    • URL(유일한 URL) 혹은 Event를 해석하고 데이터 요청 및 페이지 전환하는 일련의 과정

     

    Routing 형식
    링크형식  <a href="/"></a>
    Ajax 형식 불필요한 리소스 중복요청 방지 (새로고침x), history 관리에 불편
    https://isaac-yoon.tistory.com/19
    Hash 방식 - URI의 fragment identifier(#service, hash mark)의 고유 기능인 앵커(anchor)를 사용
    - 서버에 새로운 요청을 보내지 않으며, URI hash만 변경하여 내부에서만 이동
    - 페이지마다 고유 URL이 존재하여 Ajax 단점 보완
    - #! Hash-bang 사용

     

    // Routing 방식
    //1. Link
    <a href="/"></a>
    
    //2. Ajax  
    //html
    <li><a href="/">Home</a></li>
    <li><a href="/service">Service</a></li>
    <li><a href="/about">About</a></li>
    
    //javascript
    const routes = [
      { path: '/', component: Home },
      { path: '/service', component: Service },
      { path: '/about', component: About },
    ];
    
    const render = async path => {
      try {
        const component = routes.find(route => route.path === path)?.component || NotFound;
        $root.replaceChildren(await component());
      } catch (err) {
        console.error(err);
      }
    };
    
    //3. Hash
    //html
        <li><a href="#">Home</a></li>
        <li><a href="#service">Service</a></li>
        <li><a href="#about">About</a></li>
    
    //javascript
    const render = async () => {
      try {
        // url의 hash를 취득
        const hash = window.location.hash.replace('#', '');
        const component = routes.find(route => route.path === hash)?.component || NotFound;
        $root.replaceChildren(await component());
      } catch (err) {
        console.error(err);
      }
    };

     

     

    • Conclusion

     

    구분 History 관리 SEO 대응 사용자 경험 Server Rendering 구현 난이도 IE
    링크 방식 간단  
    ajax 방식 보통 7 이상
    hash 방식 보통 8 이상
    pjax 방식 복잡 10 이상

     

    'FrontEnd > JavaScript' 카테고리의 다른 글

    Modern JavaScript Event  (0) 2023.03.04
    Modern JavaScript Asynchronous processing model  (0) 2023.03.03
    Modern JavaScript Document Object Model  (0) 2023.03.01
    Modern JavaScript Array  (0) 2023.02.25
    Modern JavaScript 정규표현식  (0) 2023.02.18

    댓글

Designed by Tistory.