[TIL] Axios 사용방법과 전역설정

JIEUN YANG·2022년 8월 23일
1

Axios 전역설정

1. 라이브러리 설치

npm i axios

npm 외에도 bower, yarn 등이 있으니 공식 문서를 참고하여 개발환경에 맞게 설치하면 된다.



2. 인스턴스 생성


import axios from 'axios'

const axios = axios. create({
 
})

axios의 create()메서드로 인스턴스 객체를 생성한다.
이때, 함수의 인자로 옵션값을 설정할 수 있으며 url 프로퍼티는 필수, 나머지 속성은 선택사항이다.
url이 상대값이라면 ‘baseURL’을 지정하여 API 경로에 따라 create() 메서드에 전달되도록 하면 편리하다.

예를 들어

import axios from 'axios'

const axios = axios. create({
	url : 'https://test-server.net/new-makeUp',
	method : 'put',
	data : {
		className : 'vue.js',
		setTime : 'evening',
		memberList : [{name : 'yang', age : 30}, {name : 'kim', age : 33}, {name : 'lee', age : 25}]
	}
})
import axios from 'axios'

const axios = axios. create({
	url : `https://test-server.net/getlist-members?${name}?${age}`,
	method : 'get',
})

API 호출 시마다 루트 URL이 중복되기 떄문에 ‘baseURL’로 세팅해주면 동적으로 전달할 수 있다.

↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

// scr/http>index.js
import axios from '@/http/index

const axios = axios. create({
	baseURL : 'https://test-server.net/'
})

설정하고 사용하는 곳에서 아래와 같이 메서드방식과 상대URL만 명시해주면 된다.

import axios from '@/http/index'

axios.put('new-makeUp', {
		className : 'vue.js',
		setTime : 'evening',
		memberList : [{name : 'yang', age : 30}, {name : 'kim', age : 33}, {name : 'lee', age : 25}]
	})

axios.get(`getlist-members?${name}?${age}`)


3. export default 명시

// scr/http>index.js
import axios from '@/http/index

const axios = axios. create({
	baseURL : 'https://test-server.net/'
})

export default axios

axios 인스턴스 생성 후에 export default axios 로 값을 내보내야 다른 경로에서 import 문으로 사용이 가능하다.

2. interceptors

profile
violet's development note

0개의 댓글