티스토리 뷰

Web/Front - log_in

Vue_axios

잉_민 2022. 3. 22. 14:17

Axios

UserList: http://localhost:8080/test-user/list
UserInfo: http://localhost:8080/test-user/info

백엔드의 RestAPI를 호출하기 위해서 axios를 설치 한다.
Axios란? https://github.com/axios/axios

1) Axios 설치

> npm install axios vue-axios --save

2) axios 함수 파일 생성

다음과 같이 axios를 처리하는 함수를 만들어서 사용하도록 한다.

/src/store/apiUtil.js

import axios from 'axios'

const api = axios.create()

export default api

향후 위 파일에서 api.interceptors.request와 api.interceptors.response를 사용하면 편리하다. (토큰 처리에 탁월 하다)

2) Store 파일 수정

jsonplaceholder.typicode.com는 RestAPI를 테스트를 하기위해 가상의 정보를 응답해 주는 서비스 이다.

이를 이용해 다음과 같은 테스트용 Rest API를 호출 한다. (Postman에서 아래 URL의 응답을 먼저 테스트 해 보자)
사용자 리스트 GET https://jsonplaceholder.typicode.com/users
사용자 상세정보GET https://jsonplaceholder.typicode.com/users/<:id>

다음과 같이 User Store파일을 수정 한다.

/src/store/models/user.js

import api from '../apiUtil'

export default {
  state: {
    // state에 사용할 모델이나 값을 선언 한다.
    User: {
      id: 0,
      name: null,
      username: null,
      email: null
    }, // User 상세 정보용 state
    UserList: [] // User 리스트용 state
  },
  getters: {
    // getters을 통해 state값을 호출 한다.
    User: state => state.User,
    UserList: state => state.UserList
  },
  mutations: {
    // mutations는 동기적이어야 함.(비동기 사용 불가)
    setUser(state, data) {
      state.User = data
    },
    setUserList(state, data) {
      state.UserList = data
    }
  },
  actions: {
    // action은 비동기적 사용이 가능하다. (action에서 mutation을 호출하는 방법을 권장함)
    // 사용자 정보 출력
    actUserInfo(context, payload) {
      console.log('User.id', payload) // payload를 통해 검색 조건을 받을 수 있다.

      /*
      const testUserInfo = {
        id: payload,
        name: 'test',
        username: 'testUser',
        email: 'test@email.com'
      } // 이 값을 RestAPI에서 받아오면 된다.
      context.commit('setUser', testUserInfo) // mutation을 통해 User값을 세팅 한다.
      */
	  //##########################################################################
      // RestAPI로부터 UserInfo를 가져온다.
      api.get(`https://jsonplaceholder.typicode.com/users/${payload}`).then(response => {
        console.log('response', response)

        const userInfo = response && response.data // response중 userInfo만 추출 한다.
        context.commit('setUser', userInfo) // mutation을 통해 User값을 세팅 한다.
      })
      //#########################################################################
    },
    // 사용자 리스트 조회
    actUserList(context, payload) {
      console.log('searchParams', payload) // payload를 통해 검색 조건을 받을 수 있다.
      /*
      const testUserList = ['user1', 'user2', 'user3'] // 이 값을 RestAPI에서 받아오면 된다.
      context.commit('setUserList', testUserList) // mutation을 통해 UserList값을 세팅 한다.
      */

      // RestAPI로부터 UserList를 가져온다.
      api.get('https://jsonplaceholder.typicode.com/users').then(response => {
        console.log('response', response)

        const userList = response && response.data // response중 userList만 추출 한다.
        context.commit('setUserList', userList) // mutation을 통해 User값을 세팅 한다.
      })
    }
  }
}

User List 테스트

http://localhost:8080/test-user/list 에서 [Search]를 클릭하면 실제 네트워크를 통해 정보를 받아 온다.

User Info 테스트

http://localhost:8080/test-user/info 에서 User.id값에 따라 해당 사용자가 조회 된다. (범위는 1~10)

(해당 사용자 범위를 벗어나는 id를 입력해 보자. --> 서버에서 404에러가 리턴되는 것을 확인해 볼 것)

'Web > Front - log_in' 카테고리의 다른 글

로그인  (0) 2022.03.23
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함