프론트 앤드(Front-End)/React

[React Axios] Server와 HTTP 통신

RyanSin 2021. 1. 16. 14:50
반응형

- 개요

이번 시간에는 React에서 서버와 통신을 할 때 사용되는 Axios 라이브러리에 대해서 알아보겠습니다.

- 설치

npm 사용

npm install axios

 

yarm 사용

yarn add axios

 

npm 또는 yarn 패키지 매니저를 사용해서 설치를 할 수 있습니다.

 

ES5 => const axios = require('axios')

ES6 => import axios = require('axios')

 

위 방법으로 모듈을 불러와 사용할 수 있다.

- 사용법

RESTFul API 통신을 할 때 CRUD가 중요합니다.

 

C : Create(생성)

R : Read(읽기)

U : Update(수정)

D : Delete(삭제)

 

자원을 생성하고 조회하고 그리고 수정할 수 있으며 삭제도 할 수 있습니다. 

 

RESTFul API Method에는 GET, POST, PUT, PATH, DELETE 등등 있습니다.

 

저는 CRUD를 중점으로 설명하겠습니다.

 

공식 GitHub 사이트에서 각 메서드 별 설명을 확인할 수 있습니다.

 

공식 GitHub

 

API 요청을 보낼 때 받는 서버가 필요하겠죠?

 

이 글에서는 제가 만들어 놓은 Express RESTFaul API를 가지고 설명하겠습니다.

 

혹시 서버에 대한 개념이 없거나 아직 서툴으신 분들은 Fake RESTFaul API라는 무료 사이트에서 테스트를 할 수 있습니다.

 

1. Express RESTFul API any-ting.tistory.com/14

 

[Node.js] Express RESTFul API 서버 만들기

- 지난 시간 안녕하세요. 지난 시간에는 Node.js 설치 및 Express 웹 애플리케이션 프레임워크를 구축하는 시간을 가졌습니다. 혹시 지난 글을 못 보신 분들은 아래 글을 통해 설치 및 구축을 하고 오

any-ting.tistory.com

 

2. Fake RESTFul API jsonplaceholder.typicode.com/

 

JSONPlaceholder - Fake online REST API for testing and prototyping

{JSON} Placeholder Free to use fake online REST API for testing and prototyping. Powered by JSON Server + LowDB As of Dec 2020, serving ~1.8 billion requests each month.

jsonplaceholder.typicode.com

- Create(생성) : POST

서버에서 데이터(자원)를 생성할 때는 POST메서드를 사용해서 통신합니다.

 

//클라이언트 POST API 요청
axios.post('http://localhost:3000/api/users/add', {
	id: 4,
	name: '개발이 취미인 사람',
})
//성공시 then 실행
.then(function (response) {
	console.log(response);
})
//실패 시 catch 실행
.catch(function (error) {
	console.log(error);
});

//서버 소스 코드

//임시 데이터
const users = [
 { id: 1, name: "유저1" },
 { id: 2, name: "유저2" },
 { id: 3, name: "유저3" }
];

/**
 * @path {POST} http://localhost:3000/api/users/add
 * @description POST Method
 * 
 *  POST 데이터를 생성할 때 사용된다.
 *  req.body에 데이터를 담아서 보통 보낸다.
 */
app.post("/api/users/add", (req, res) => {

    // 구조분해를 통해 id 와 name을 추출
    const { id, name } = req.body

    //concat 함수는 자바스크립트에서 배열 함수이다. 새로운 데이터를 추가하면 새로운 배열로 반환한다.
    const user = users.concat({id, name});

    res.json({ok: true, users: user})
})

- 요청 된 결과(응답) 데이터

응답 데이터

- Read(조회) : GET

 

서버에서 데이터(자원)를 조회할 때는 GET메서드를 사용해서 통신합니다.

 

1. 전체 데이터 조회

//클라이언트 GET API 요청(서버에 전달 데이터 없이 데이터 조회 "전체 데이터 조회")
axios.get('http://localhost:3000/api/users')
//성공시 then 실행
.then(function (response) {
	console.log(response);
})
//실패 시 catch 실행
.catch(function (error) {
	console.log(error);
})
//성공이던 실패던 항상 실행
.then(function () {
	// always executed
});

//서버 소스 코드

//임시 데이터
const users = [
 { id: 1, name: "유저1" },
 { id: 2, name: "유저2" },
 { id: 3, name: "유저3" }
];

/**
 * @path {GET} http://localhost:3000/api/users
 * @description 요청 데이터 값이 없고 반환 값이 있는 GET Method
 */
app.get("/api/users", (req, res) => {

    //유저 정보 반환
    res.json({ok: true, users: users});
})

- 요청 된 결과(응답) 데이터

응답 데이터

2. 특정 데이터 조회 (3가지 방식)

 

1-1. 경로(Path)에 값을 설정해서 보낸다. (게시판에 상세보기 페이지에서 사용된다.)

Ex) 티스토리 : any-ting.tistory.com/14 << 요기 :)

//클라이언트 GET API 요청(서버에 특정 데이터 전송 "특정 데이터 조회")

//Param (Path)요청
axios.get(`http://localhost:3000/api/users/${1}`)
	//성공시 then 실행
.then(function (response) {
	console.log(response);
})
//실패 시 catch 실행
.catch(function (error) {
	console.log(error);
})
	//성공이던 실패던 항상 실행
.then(function () {
	// always executed
});


//서버 소스 코드

//임시 데이터
const users = [
 { id: 1, name: "유저1" },
 { id: 2, name: "유저2" },
 { id: 3, name: "유저3" }
];

/**
 * @path {GET} http://localhost:3000/api/users/:user_id
 * @description Path Variables 요청 데이터 값이 있고 반환 값이 있는 GET Method 
 * 
 *  Path Variables 방식
 * 
 *  ex) 아래 GET 주소 에서 :user_id 는 서버에서 설정한 주소 키 값이다.
 *      값을 찾을 때는 req.params.user_id 로 값을 찾는다.
 * 
 *  *주의 사항*
 *  :user_id 이 부분은 변수이기 때문에 
 *  경로가 /users/1 이거나 /users/2 이거 일때 둘다 라우터를 거치게 된다.
 *  그렇기 때문에 다른 라우터 보다 아래 있어야 한다.
 */
app.get("/api/users/:user_id", (req, res) => {

    const user_id = req.params.user_id

    //filter라는 함수는 자바스크립트에서 배열 함수이다. 필터링을 할때 많이 사용된다 필터링한 데이터를 새로운 배열로 반환한다.
    const user = users.filter(data => data.id == user_id);

    res.json({ok: true, user: user})
})

- 요청 된 결과(응답) 데이터

응답 데이터

1-2. Query String 방식

//클라이언트 GET API 요청(서버에 특정 데이터 전송 "특정 데이터 조회")
  
//Query요청(방식1)[경로에 데이터가 노출된다.]
axios.get(`http://localhost:3000/api/users/user?user_id=${1}`)
//성공시 then 실행
.then(function (response) {
   console.log(response);
})
//실패 시 catch 실행
.catch(function (error) {
   console.log(error);
})
//성공이던 실패던 항상 실행
.then(function () {
   // always executed
});

//Query요청(방식2)[경로에 데이터가 노출되지 않고 params라는 항목에 데이터가 담겨간다. :)]
axios.get(`http://localhost:3000/api/users/user`,
{
 	params: {
		user_id: 1
	}
})
//성공시 then 실행
.then(function (response) {
	console.log(response);
})
//실패 시 catch 실행
.catch(function (error) {
	console.log(error);
})
//성공이던 실패던 항상 실행
.then(function () {
	// always executed
});
 
 
//서버 소스 코드

//임시 데이터
const users = [
 { id: 1, name: "유저1" },
 { id: 2, name: "유저2" },
 { id: 3, name: "유저3" }
];

/**
 * @path {GET} http://localhost:3000/api/users/user?user_id=1
 * @description Query Params 요청 데이터 값이 있고 반환 값이 있는 GET Method 
 * 
 *  Query Params 방식
 *  user 뒤에 user_id변수를 통해 값을 찾아 올수 있다.
 *  &를 통해 두번째 변수를 받아서 사용할 수 있다.(/user?user_id=1&name="유저1")
 * 
 */
app.get("/api/users/user", (req, res) => {

    const user_id = req.query.user_id

    //filter라는 함수는 자바스크립트에서 배열 함수이다. 필터링을 할때 많이 사용된다 필터링한 데이터를 새로운 배열로 반환한다.
    const user = users.filter(data => data.id == user_id);

    res.json({ok: false, user: user})
})

- 요청 된 결과(응답) 데이터

 

요청 방식 1번

params 항목이 없다.

요청 방식 2번

params 항목 user_id 데이터 있다.

 

- Update(수정) : PUT & PATCH

//클라이언트 PUT & PATCH API 요청(데이터 전체 수정 및 단일 수정)

//전체 데이터 수정
axios.put('http://localhost:3000/api/users/update', {
  id: 1,
  name: '개발이 취미인 사람',
})
//성공시 then 실행
.then(function (response) {
	console.log(response);	
})
//실패 시 catch 실행
.catch(function (error) {
	console.log(error);
});

//특정 데이터 수정
axios.patch(`http://localhost:3000/api/user/update/${1}`, {
	name: '개발이 취미인 사람'
})
//성공시 then 실행
.then(function (response) {
	console.log(response);
})
//실패 시 catch 실행
.catch(function (error) {
	console.log(error);
});


//서버 소스 코드

//임시 데이터
const users = [
 { id: 1, name: "유저1" },
 { id: 2, name: "유저2" },
 { id: 3, name: "유저3" }
];

/**
 * @path {PUT} http://localhost:3000/api/users/update
 * @description 전체 데이터를 수정할 때 사용되는 Method
 */
app.put("/api/users/update", (req, res) => {
    
    // 구조분해를 통해 id 와 name을 추출
    const { id, name } = req.body

    //map 함수는 자바스크립트에서 배열 함수이다. 요소를 일괄적으로 변경할 때 사용됩니다.
    const user = users.map(data => {

        if(data.id == id) data.name = name

        return {
            id: data.id,
            name: data.name
        }
    })

    res.json({ok: true, users: user})
})

/**
 * @path {PATCH} http://localhost:3000/api/user/update/:user_id
 * @description 단일 데이터를 수정할 때 사용되는 Method
 */
app.patch("/api/user/update/:user_id", (req, res) => {

    const { user_id} = req.params
    const { name } = req.body

    //map 함수는 자바스크립트에서 배열 함수이다. 요소를 일괄적으로 변경할 때 사용됩니다.
    const user = users.map(data => {

        if(data.id == user_id) data.name = name

        return {
            id: data.id,
            name: data.name
        }
    })

    res.json({ok: true, users: user})
})

 

- 요청 된 결과(응답) 데이터

 

PUT 결과
PATCH 요청

결과 값을 보면 두 개가 비슷하지만 RESTFaul API에 대한 설계에 따라 달라질 수 있다. 이 부분은 고려해서 만들었으면 좋겠습니다.

 

- Delete(삭제) : DELETE

데이터를 삭제할 때 사용되는 메서드

//클라이언트 DELETE API 요청(데이터 삭제)

axios.delete('http://localhost:3000/api/user/delete',{
params: {
	user_id: 1
}
})
//성공시 then 실행
.then(function (response) {
	console.log(response);
})
//실패 시 catch 실행
.catch(function (error) {
	console.log(error);
});

//서버 소스 코드

//임시 데이터
const users = [
 { id: 1, name: "유저1" },
 { id: 2, name: "유저2" },
 { id: 3, name: "유저3" }
];

/**
 * @path {DELETE} http://localhost:3000/api/user/delete
 * @description 데이터 삭제
 * 
 */
app.delete("/api/user/delete", (req, res) => {

    const user_id = req.query.user_id

    //filter라는 함수는 자바스크립트에서 배열 함수이다. 필터링을 할때 많이 사용된다 필터링한 데이터를 새로운 배열로 반환한다.
    const user = users.filter(data => data.id != user_id );

    res.json({ok: true, users: user})
})

- 요청된 결과(응답) 데이터

 

Params에 담아서 보내도 되고 경로에 변수를 설정해서 보내도 됩니다. 

 

이번 시간에는 Axios를 활용해서 CRUD에 대해 알아봤습니다.

소스 저장소

클라이언트 소드

GitHub : github.com/Ryan-Sin/React-Axios

 

Ryan-Sin/React-Axios

Contribute to Ryan-Sin/React-Axios development by creating an account on GitHub.

github.com

- 참고 사이트

GitHub Axios : github.com/axios/axios

 

axios/axios

Promise based HTTP client for the browser and node.js - axios/axios

github.com