일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- rebase -i
- axios
- local branch
- TypeScript
- chatbot
- 리액트네이티브
- insert와 update 한꺼번에 하기
- 파이썬 챗봇
- pure CSS
- reactnative
- git
- 시차 스크롤
- frontend
- EpPlus
- 개발
- vuejs
- Python
- 로컬 브랜치
- insert into
- oracle
- 챗봇
- SQL
- 브랜치 삭제
- c#
- 다중insert
- git command
- 동시insert
- 시차애니메이션
- 텔레그램 챗봇
- util fuction
- Today
- Total
DOG FOOT
[Vue js] Vue js에서 axios를 이용한 HTTP 통신 구현하기. 본문
깃허브 블로그에 방문자 수 세는 기능을 안달았더니 유입량을 알 방도가 없어서 이번 포스트는 티스토리에 작성하기로 했다.
아래 이사한 블로그는 2주 뒤까지는 댓글 기능과 방문자수 기능을 달 생각이다...
이번 포스트는 아래 포스트에서 연재중인 PWA 모임 어플리케이션에서 HTTP 통신부 구현할 때 했던 생각과 코드다.
https://junnis0123.github.io/2020/07/25/codingTogether.html
[Vue js] Vue js + PWA 모임 어플리케이션 만들기 1.기획 - DOG FOOT
안녕하세요, 김선진입니다. 기존에 개발하던 딜리장터 프로젝트 에서 firebase 로그인을 버리고 코그니토 로그인으로 롤백하는 걸로 결정났습니다…. 열심히 달았는데 슬퍼져 vue 개발 하면서 기��
junnis0123.github.io
이사한 깃허브 블로그도 놀러오세요.
auth를 제공하는 웹개발을 하면서 요청하는 api 특성에 따라 request header를 다르게 설정하고 싶은 경우가 있다.
또는 Response Body에 맞춰서 동일 로직을 사용하는 경우 중복 코드를 제거하고 싶은 욕구가 생긴다.
이번 프로젝트는 서버 개발자가 response를 깔끔하게 만들어줘서 특히 두번째 욕구가 생겼다.
Ajax요청은 axios라이브러리를 이용했다. 11M이나 쓰고 있는데다 엄청 가볍고 문법도 간결하다.
HTTP 및 Ajax 설명은 MDN링크를 걸어둘테니 읽어보는 걸 추천함.
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX
Ajax
A synchronous J avaScript a nd X ML, while not a technology in itself, is a term coined in 2005 by Jesse James Garrett, that describes a "new" approach to using a number of existing technologies together
developer.mozilla.org
HTTP
Hypertext Transfer Protocol (HTTP) is an application-layer protocol for transmitting hypermedia documents, such as HTML. It was designed for communication between web browsers and web servers, but it can also be used for other purposes. HTTP follows a clas
developer.mozilla.org
VueJS에서 개발하고 있기 떄문에 VueJS기준이다.
먼저 npm install axios 또는 package.json 파일의 dependencies에 "axios": "^0.19.2",를 한 줄 추가해주고 npm install을 실행해주자.
나는 auth가 있는 axios config와 auth가 없는 axios config는 다르게 하지만 response body는 동일한 모양이며 동일한 사후 처리를
해 줄 예정이기 때문에 2개의 axios 객체를 만들고 필요에 따라 각 객체를 생성해서 반환해주는 axios factory를 만들었다.
1. auth가 없는 axios 설정
import axios from 'axios';
axios.defaults.baseURL = process.env.VUE_APP_API_BASE;
axios.interceptors.response.use((response) => response,
async (err) => Promise.reject(err.response.data));
export default axios;
2. auth가 있는 axios 설정
import axios, { AxiosRequestConfig } from 'axios';
const apiAxios = axios.create();
apiAxios.interceptors.request.use((config) => {
const con: AxiosRequestConfig = config;
con.headers = {
Authorization: `Bearer ${token)}`, //token은 뭐든 당신의 JWT 토큰을 넣으면 됨.
};
return con;
}, async (err) => {
const error = err;
return Promise.reject(error);
});
export default apiAxios;
3. HTTP Factory 작성
import HTTP from '@/services/axios/HTTP';
import { AxiosResponse } from 'axios';
import HTTPAuth from ''@/services/axios/HTTPAuth';
enum AxiosType {
Default,
Auth,
}
const createAxios = (type: AxiosType) => {
switch (type) {
case AxiosType.Default:
default:
return HTTP;
case AxiosType.Auth:
return HTTPAuth;
}
};
export default function useAxios(type: AxiosType) {
const axios = createAxios(type);
const get = async<T = AxiosResponse> (url: string, params?: object) => {
try {
const result = await axios.get<T>(url, params);
return result.data;
} catch (e) {
alert(e.message);
return false;
}
};
const post = async<T = AxiosResponse> (url: string, formData?: FormData) => {
try {
const result = await axios.post<T>(url, formData);
return result.data;
} catch (e) {
alert(e.message);
return false;
}
};
return {
get,
post,
};
}
팩토리에서는 HTTP 모듈별로 enum을 만들어 할당해주고 enum을 받아 타입을 생성해주는 create 함수를 뒀다.
(enum대신 type 써도 무방함)
팩토리는 get, post, (추후 다른 메소드 추가 가능)을 리턴해서 사용하는 곳에서는 편하게 get, post만 호출해서 사용하고 결과만 받을 수 있다. 결과를 포스팅하려고 했는데 서버가 갑자기 CORS나서 고쳐지면 수정하겠습니다.
그럼 이만~
'개발새발 > Frontend' 카테고리의 다른 글
[Typescript] Interface (0) | 2020.11.08 |
---|---|
[VueJS] VueStyledComponent (0) | 2020.09.28 |
[Vue.js] 동적으로 rowspan이 있는 table 만들기 (0) | 2020.01.21 |
[Vue.js] 이모지 입력이 되지 않는 TextArea Component 만들기 (0) | 2020.01.20 |
[Vue] regex를 적용한 TextInput에서 값 업데이트가 제대로 되지 않는 현상 (1) | 2019.12.24 |