Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 1 addition & 10 deletions src/apis/auth.api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { LoginProps } from '@/pages/LoginPage';
import { JoinProps } from '@/pages/JoinPage';
import httpClient from './http.api';
import { httpClient } from './http.api';

export const join = async (data: JoinProps) => {
const response = await httpClient.post('/api/users/join', data);
Expand All @@ -12,11 +11,3 @@ export interface LoginResponse {
success: boolean;
token?: string;
}

export const login = async (data: LoginProps) => {
const response = await httpClient.post<LoginResponse>(
'/api/users/login',
data
);
return response.data;
};
84 changes: 51 additions & 33 deletions src/apis/http.api.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import axios, {
AxiosInstance,
AxiosRequestConfig,
AxiosHeaders,
AxiosRequestHeaders,
} from 'axios';
import axios, { AxiosRequestConfig } from 'axios';

const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3333';
const BASE_URL = import.meta.env.VITE_API_BASE_URL;
const DEFAULT_TIMEOUT = 30000; // 요청 제한 시간

// 토큰 관리 함수
Expand All @@ -21,57 +16,80 @@ function removeToken() {
localStorage.removeItem('token');
}

// Axios 인스턴스 생성 함수
export const createClient = (config?: AxiosRequestConfig): AxiosInstance => {
export const createClient = (config?: AxiosRequestConfig) => {
const token = getToken(); // 토큰 가져오기
const axiosInstance = axios.create({
baseURL: BASE_URL,
timeout: DEFAULT_TIMEOUT,
headers: {
'Content-Type': 'application/json',
Authorization: token ? `Bearer ${token}` : '',
},
withCredentials: true,
...config,
});

// 요청 인터셉터: Authorization 헤더 동적 설정
axiosInstance.interceptors.request.use(
(config) => {
const accessToken = getToken(); // 여기서 getToken()을 호출하여 실제로 사용
if (accessToken) {
if (
config.headers &&
'set' in config.headers &&
typeof (config.headers as AxiosHeaders).set === 'function'
) {
// AxiosHeaders 타입으로 헤더를 다루는 경우
(config.headers as AxiosHeaders).set(
'Authorization',
`Bearer ${accessToken}`
);
} else {
// 일반 객체로 헤더를 다루는 경우
config.headers = {
...config.headers,
Authorization: `Bearer ${accessToken}`,
} as AxiosRequestHeaders;
}
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
console.log('Request Headers:', config.headers); // 디버깅용 로그
return config;
},
(error) => {
console.error('Request Error:', error);
return Promise.reject(error);
}
);

axiosInstance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
// 로그인 만료 처리
if (error.response.status === 401) {
removeToken();
window.location.href = '/login';
return;
}
return Promise.reject(error);
}
);

return axiosInstance;
};

// 기본 Axios 인스턴스 생성
export const httpClient = createClient();

// 토큰 관련 함수 export
export { setToken, removeToken, getToken };

export default httpClient;
// 공통 요청 부분

type RequestMethod = 'get' | 'post' | 'put' | 'delete';

export const requestHandler = async <R = undefined, T = undefined>(
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요 친구는 어디에 쓰이는 걸까요?

메소드를 함수형으로 호출하는 대신 string 인자를 통해 전달하는 것이 더 좋은 방식일까요?

method: RequestMethod,
url: string,
payload?: T
) => {
let response;

switch (method) {
case 'post':
response = await httpClient.post<R>(url, payload);
break;
case 'get':
response = await httpClient.get<R>(url);
break;
case 'put':
response = await httpClient.put<R>(url, payload);
break;
case 'delete':
response = await httpClient.delete<R>(url);
break;
}

return response.data;
};
6 changes: 3 additions & 3 deletions src/apis/maindata.api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import httpClient from '@/apis/http.api';
import { mainData } from '@/model/main.model';
import { httpClient } from './http.api';
import { mainData } from '@/types/main.model';

export const fetchMainData = async () => {
const response = await httpClient.get<mainData>('/api/main');
Expand All @@ -8,4 +8,4 @@ export const fetchMainData = async () => {
} catch {
throw Error;
}
}
};
13 changes: 0 additions & 13 deletions src/apis/mainpost.api.ts

This file was deleted.

4 changes: 4 additions & 0 deletions src/assets/DefaultAvatar.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
95 changes: 0 additions & 95 deletions src/components/AuthButton.tsx

This file was deleted.

12 changes: 2 additions & 10 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
import styled from 'styled-components';
import logo from '@/assets/logo.svg';
import Avatar from './ui/atoms/Avator';
import AuthButton from './AuthButton';
import MenuButton from './MenuButton';

const Header = () => (
<HeaderContainer>
<HeaderWrapper>
<img src={logo} alt='Logo' />
<div>
<Avatar
src='https://jmagazine.joins.com/_data2/photo/2021/04/838745483_D5lXOQuU_5.jpg'
size='small'
alt='User Avatar'
/>
</div>
</HeaderWrapper>
<AuthButton />
<MenuButton />
</HeaderContainer>
);

Expand Down
Loading