Posts REST API를 쓰는 이유
Post
Cancel

REST API를 쓰는 이유

ymillonga-sns라는 풀스택 프로젝트를 만들 때 백엔드 서버를 만들면서 가장 헷갈렸던 부분이 프론트에서 axios로 요청을 보낼 때 어떤 메소드(get, post, patch, delete)로 보내야 하는지, 백엔드 서버에서는 그 요청을 받아 어떤 데이터를 보내주는지였다.
예를 들어 프론트 서버에서 로그인 요청을 보낼 때 post 메소드를 쓰는 것이 그랬다. 비밀번호가 들어가기 때문에 get처럼 url에 데이터값이 노출되는 메소드는 안되고 그렇다고 patch,put처럼 데이터값을 바꿔주는 것도 아니니 post를 쓰는 것이다.

front>saga>user.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function loginAPI(data) {
  return axios.post('/user/login', data);
}
function* login(action) {
  try {
    const result = yield call(loginAPI, action.data);

    yield put({
      type: LOG_IN_SUCCESS,
      data: result.data,
    });
  } catch (err) {
    console.error(err);
    yield put({
      type: LOG_IN_FAILURE,
      error: err.response.data,
    });
  }
}

back>routes>user.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
router.post('/login', isNotLoggedIn, (req, res, next) => {
  passport.authenticate('local', (err, user, info) => {
    if (err) {
      console.error(err);
      return next(err);
    }
    if (info) {
      return res.status(401).send(info.reason);
    }
    return req.login(user, async (loginErr) => {
      if (loginErr) {
        console.error(loginErr);
        return next(loginErr);
      }
      const fullUserWithoutPassword = await User.findOne({
        where: { id: user.id },
        attributes: {
          include: ['id', 'nickname'],
        },
        include: [
          {
            model: Post,
            attributes: ['id'],
          },
          {
            model: User,
            as: 'Followings',
            attributes: ['id', 'nickname'],
          },
          {
            model: User,
            as: 'Followers',
            attributes: ['id', 'nickname'],
          },
          {
            model: User,
            as: 'Ignorings',
            attributes: ['id'],
          },
        ],
      });

      return res.status(200).json(fullUserWithoutPassword);
    });
  })(req, res, next);
});


백엔드 서버에서는 예를 들어 http://localhost:3051//user/login이라는 주소로 프론트에서 보낸 데이터 값을 받는다
백엔드 서버의 return res.status(200).json(fullUserWithoutPassword); 라는 부분에서 json으로 보낸 결과값이 프론트 서버의 saga에 있는 const result = yield call(loginAPI, action.data); 의 action.data에 담긴다.


이제 와 생각해보니 프로젝트에서 REST API 방법를 사용해서 그래도 백엔드 서버와 프론트엔드 서버 간의 통신이 덜 헷갈릴 수 있었던 것 같다. 이처럼 REST API 방법을 사용하면 주소와 메서드만 보고 요청의 내용을 알아볼 수 있다는 장점이 있다. 그래서 개발자간의 소통도 쉽고 개발 시 혼선도 덜 빚어진다고 한다.
REST는 서버의 자원을 정의하고 자원에 대한 주소를 지정하는 방법을 가리킨다. REST API 방법에 따라 주소를 만들면 이 주소가 서버의 자원를 정의한다. 클라이언트 측에서는 요청의 내용을 표현할 수 있다.
REST API를 이용해 HTTP 통신을 사용하면 iOS, 안드로이드, 웹, 다른 서버가 모두 같은 주소로 서버에 요청을 보낼 수 있다. 언어에 상관없이 HTTP를 사용하는 다양한 플랫폼에서 동시에 이 주소를 사용할 수 있는 것이다. 이렇게 서버와 클라이언트를 분리하면 추후에 서버를 확장할 때 클라이언트에 구애되지 않아 좋다.


출처:
zerocho blog: REST API
node 교과서

This post is licensed under CC BY 4.0 by the author.

REACT JSX속성

SequelizeUniqueConstraintError

Comments powered by Disqus.