[프론트엔드_개발] JSON server와 axios

혯승·2023년 5월 22일
0

프론트엔드_개발

목록 보기
7/9
post-thumbnail

REST API

📖 1. REST API란?

일번적인 웹 거버 프로그램은, 웹브라우저창에 그려질 HTML 태그들을 출력

  • javascript앱을 위한 서버 프로그램은, 앱이 사용할 데이터 출력.
    보통 JSON형식이나 XML형식으로 데이터 출력
    ▶︎ 위와 같은 목적으로 구현된 웹 서버 프로그램을 RESTful Service라고 함, 클라이언트 앱을 위한 웹서버 프로그램

  • RESTful Service가 제공하는 URL목록이 REST API
    ▶︎ 클라이언트 앱은 REST API URL을 서버에 요청해서, 서버와 데이터를 주고 받음

  • 클라이언트 앱과 RESTful Service 서버 사이의 통신은 당연히 HTTP, HTTPS 프로토콜을 사용한다.

📥 request method

일반적인 웹 서버 프로그래밍에서, 웹브라우저가 웹서버를 호출하는 요청 방식(request method)은 GET, POST 방식이 있음

  • REST API에서는 GET, POST, PUT, DELETE 요청 방식을 사용
    GET : 데이터 조회 요청
    POST : 신규 데이터 등록 요청
    PUT : 데이터 수정 요청
    DELETE : 데이터 삭제 요청

2.JSON형식

JSON(JavaScript Object Notation) : javascript 언어의 객체와 배열 문법으로 데이터를 표현한 것
▶︎ JSON 형식에서는 반드시 속성명을 따옴표로 묶어야함

JSON형식의 예

//객체
{ "name": "홍길동", "age": 16 }

//배열
[{ "name": "홍길동", "age": 16 }, { "name": "임꺽정", "age": 19 }];

🔗 serialization / unserialization

  • serialization : 객체나 배열을 byte 배열이나 문자열로 변환, 객체나 배열을 JSON형식의 문자열로 반환하는 것 ➡️ 객체,배열 ▶︎ JSON
  • unserialization : JSON형식의 문자열로부터 객체나 배열 생성하는 것 ➡️ JSON ▶︎ 객체,배열

➡️ 객체나 배열을 파일에 저장하거나, 네트워크로 전송하기 위해 serialize하고 파일에서 읽거나 네트워크로 전송 받은 데이터에서 원래 객체나 배열을 복구하기 위해 unserialize한다.
클라이언트 앱에서 서버로 데이터를 보낼 때, JSON 형식의 문자열로 serialize 해서 보내야 한다.
서버에서 받아온 JSON 형식의 문자열을 unserialize 해서 데이터 객체를 만들어야 한다.

  • serialize 예시
let person = { name: "홍길동", age: 16 };

let s = JSON.stringify(person); //객체 -> JSON형식의 문자열
console.log(s);
  • unserialize 예시
let s = '{"name":"홍길동","age":16}';

let person = JSON.parse(s);//JSON형식의 문자열로부터 객체를 생성해서 리턴
console.log(person);
  • deep copy
    : serialize -> unserialize하면 deepcopy
let a1 = [{ "name": "홍길동", "age": 16 }, { "name": "임꺽정", "age": 19 }];

//deep copy
let s = JSON.stringify(a1);
let a2 = JSON.parse(s);

console.log(a2);
  • deep compare
    : serialize 이용항 deep equals 쉽게 구현(JS에서는 eqauls 메소드 없음)
let a1 = [{ "name": "홍길동", "age": 16 }, { "name": "임꺽정", "age": 19 }];

let s = JSON.stringify(a1);
let a2 = JSON.parse(s);

console.log(a2);

if (JSON.stringify(a1) == JSON.stringify(a2)) // true 이다, 내용 비교(String 비교) -> equality
  console.log("equals");

console.log(a1 == a2); // false 이다, 참조 주소 비교 -> identity

📚 3.axios 라이브러리

: javascript 클라이언트 앱에서 백엔드 서버를 호출하기 위해 사용하는 라이브러리 중 하나

1) 사용법

  • 라이브러리 설치
npm install axios
  • import
import axios from 'axios'
  • 데이터 조회 요청 GET
axios.get("http://localhost:3000/students")
     .then(response => this.students = response.data )
     .catch(error => console.log(error)); //통신 에러
  • 신규 데이터 등록 요청 POSt
axios.post("http://localhost:3000/students", this.student) //자동으로 JSON포맷으로 인코딩되어 서버로 전달
     .then(response => this.reload()) //작업 결과 전송하면 호출
     .catch(error => console.log(error));
  • 데이터 수정 요청 PUT
axios.put("http://localhost:3000/students/3", this.student)//3은 id, 수정할 데이터는 this.student
     .then(response => this.reload())
     .catch(error => console.log(error));
  • 데이터 삭제 요청 DELETE
axios.delete("http://localhost:3000/students/3")
     .then(response => this.reload())
     .catch(error => console.log(error));

2) 비동기 I/O

파일 I/O, 네트워크 통신 I/O가 있음
javascript I/O은 대부분 비동기(asynchronous)방식

  • 동기 방식
    (1) student = axios.get(' http://localhost:3000/students') 응답이 올 때까지, 프로세스는 block
    (2) print(student)

  • get 요청 구현 방법 #1

  axios.get(' http://localhost:3000/students')
    .then(response => {
      this.students = response.data;
    })

javascript로 구현한 백엔드 호출 요청은 비동기로 실행
(1) axios.get 메소드는 즉시 리턴
(2) then 메소드 호출, 콜백 함수를 등록
(3) 서버 응답(response)이 도착하면, then 메소드로 등록한 콜백 함수 호출

  • get 요청 구현 방법 #2
async function test1() {
  const response = await axios.get(' http://localhost:3000/students');
  this.students = response.data;
}

await 키워드가 있는 함수는 맨 앞에 async 키워드를 붙여야함
▶︎ javascript의 비동기 작업을 동기 작업처럼 편하게 구현
(1) axios.get 메소드는 즉시 리턴하지 않음. 서버의 응답이 웹브라우저에 도착하면 그 때 리턴(리턴 값은 서버의 응답)
(2) 그 다음줄 실행

그러나 여전히 axios.get 메소드는 비동기로 실행

4.JSON server

: 테스트를 하기 위해 필요한 백엔드 서버를 간단하게 만들어주는 도구

테스트 데이터가 들어있는 JSON 파일만 만들면 (예: students-db.json),이 파일에 들어있는 데이터를 조회, 등록, 수정, 삭제하기 위한 백엔드 REST API 서비스가 자동으로 실행된다.

  • 설치
npm install -g json-server

-g : PC에 설치

  • 실행
json-server --watch students-db.json

💻 student1 프로젝트

vue create student1
  • student1 프로젝트에 json-server 설치
npm install -g json-server

students-db.json 생성

src/students-db.json 에 구현

API 테스트

  • json-server 실행
json-server --watch students 전체 목록
http://localhost:3000/students

departments 전체 목록
http://localhost:3000/departments

학번 오른차순 정렬
http://localhost:3000/students?_sort=studentNo

학번 내림차순 정렬
http://localhost:3000/students?_sort=studentNo&_order=DESC

학번으로 조회
http://localhost:3000/students?studentNo=201532008

학과로 조회
http://localhost:3000/students?departmentId=3

pagination
http://localhost:3000/students?_page=3&_sort=id
id 오름차순으로 3번째 페이지 (한 페이지에 10개 레코드)

http://localhost:3000/students?_page=3&_sort=id&_limit=15
id 오름차순으로 3번째 페이지 (한 페이지에 15개 레코드)

등록/수정/삭제
http://localhost:3000/students URL을 POST/PUT/DELETE 요청한다.
전송할 데이터는 JSON 포멧이어야 한다.

POST 요청
http://localhost:3000/students URL
등록할 객체가 파라미터로 전달되어야 한다.

PUT 요청
http://localhost:3000/students/3 URL id값이 URL에 포함되어야 함
수정할 객체가 파라미터로 전달되어야 한다.

DELETE 요청
http://localhost:3000/students/3 URL id값이 URL에 포함되어야 함
-db.json

0개의 댓글

관련 채용 정보