Skip to content

Commit

Permalink
Merge pull request #41 from Goorm-Lucky7/dev
Browse files Browse the repository at this point in the history
[PR] dev to main branch
  • Loading branch information
gamjatan9 authored May 8, 2024
2 parents a608310 + 0894d9f commit d2ab0ff
Show file tree
Hide file tree
Showing 11 changed files with 89 additions and 91 deletions.
48 changes: 25 additions & 23 deletions src/apis/authAxios.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,36 @@
import axios from 'axios';
import { getNewRefreshToken } from './refresh';

export const getAuthAxios = (token: string) => {
export const getAuthAxios = (accessToken?: string) => {
const headersOption = accessToken
? {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
}
: {
'Content-Type': 'application/json',
};

const authAxios = axios.create({
baseURL: 'http://211.206.94.24:9999',
headers: {
'Content-Type': 'application/json',
access: `Bearer ${token}`,
},
headers: headersOption,
withCredentials: true,
});

authAxios.interceptors.response.use(
(response) => response, // 성공 응답은 그대로 반환
authAxios.interceptors.response.use(async (response) => {
if (response.status === 200) {
return response;
} else {
if (response.data && response.data.accessToken) {
const accessToken = response.data.accessToken;
localStorage.setItem('access', accessToken); // 새 토큰을 로컬 스토리지에 저장
console.log('access token 재발급');

async (error) => {
if (error.response && error.response.status === 401) {
try {
const { accessToken } = await getNewRefreshToken(); // 새로운 토큰 가져오기
error.config.headers['access'] = `Bearer ${accessToken}`;
localStorage.setItem('access', accessToken);
return authAxios(error.config);
} catch (refreshError) {
// 리프레시 토큰 실패 처리
console.error('Failed to refresh token:', refreshError);
return Promise.reject(refreshError);
}
// 헤더에 새 토큰 반영
//authAxios.defaults.headers.access = `Bearer ${accessToken}`;
}
return Promise.reject(error); // 다른 모든 에러는 그대로 반환
},
);
return response;
}
});

return authAxios;
};
9 changes: 1 addition & 8 deletions src/apis/like/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,7 @@ import { getAuthAxios } from '../authAxios';

// 좋아요 수 업데이트 구문
const updateLike = async (postId: number): Promise<void> => {
const access = localStorage.getItem('access');

if (!access) {
console.error('Access token is missing or invalid');
throw new Error('Access token is missing or invalid');
}

const authAxios = getAuthAxios(access);
const authAxios = getAuthAxios();

try {
const response = await authAxios.post('/api/like', postId);
Expand Down
4 changes: 2 additions & 2 deletions src/apis/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ const fetchPosts = async ({ pageParam = 1, limit = 2 }: FetchParams): Promise<Li
}

const authAxios = getAuthAxios(access);

try {
const response = await authAxios.get<List>(
`https://baa4852a-d5cb-4d7d-9716-715686200726.mock.pstmn.io/api/posts?page=${pageParam}&limit=${limit}`,
`/api/posts?page=${pageParam}&limit=${limit}`,
);
return response.data;
} catch (error) {
Expand Down
3 changes: 2 additions & 1 deletion src/apis/mypage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const getMyPage = async () => {
}

const authAxios = getAuthAxios(access);
const response = await authAxios.get('/api/mypage');
const response = await authAxios.get('/api/mypage/users');
console.log(response.data);
return response.data;
};
12 changes: 0 additions & 12 deletions src/apis/refresh.ts

This file was deleted.

14 changes: 11 additions & 3 deletions src/apis/userapi.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Login, SignUp } from '@/types/auth';
import axios from 'axios';
import { getAuthAxios } from './authAxios';

/** LOGIN API **/
export const postLogin = async ({ email, password }: Login) => {
const data = { email, password };
const response = await axios.post(`/api/login`, data);
const authAxios = getAuthAxios();
const response = await authAxios.post('/api/login', data);
return response.data;
};

Expand All @@ -29,6 +30,13 @@ export const postSignup = async ({
introduce,
profileImage,
};
const response = await axios.post(`/api/signup`, data);
const authAxios = getAuthAxios();
const response = await authAxios.post('/api/signup', data);
return response.data;
};

export const logout = () => {
// 로컬 스토리지에서 토큰 제거
localStorage.removeItem('access');
window.location.href = '/login';
};
4 changes: 2 additions & 2 deletions src/components/loginForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ export default function LoginForm() {
const onSubmit: SubmitHandler<Login> = async (data) => {
try {
const response = await postLogin(data);
const accessToken = response;
localStorage.setItem('access', accessToken); //refreshToken은 쿠키에..
const accessToken = response.accessToken;
localStorage.setItem('access', accessToken);
console.log('로그인 성공:', response);
navigate('/mypage');
} catch (error) {
Expand Down
16 changes: 10 additions & 6 deletions src/components/mypage/userInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,25 @@ import { User } from '@/types/auth.ts';

const UserInfo = () => {
const [userData, setUserData] = useState<User>({
nickname: 'Soohyun Kim',
profileImage: null,
email: '[email protected]',
introduce: 'hello',
email: '',
nickname: '',
github: '',
blog: '',
introduce: '',
profileImage: '',
});

useEffect(() => {
const fetchUserData = async () => {
const data = await getMyPage();
if (data) {
setUserData({
nickname: data.nickname,
profileImage: data.profileImage,
email: data.email,
nickname: data.nickname,
github: data.github,
blog: data.blog,
introduce: data.introduce,
profileImage: data.profileImageResDto?.fileUrl,
});
}
};
Expand Down
60 changes: 30 additions & 30 deletions src/components/nav/navItems.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
import { IconValues } from "../shared/icon";
import { IconValues } from '../shared/icon';

interface NavItemsProps {
icon: IconValues;
label : string;
path : string;
icon: IconValues;
label: string;
path: string;
}

export const navItems: NavItemsProps[] = [
{
icon: 'home',
label: 'Home',
path : '/'
},
{
icon: 'search',
label: 'Search',
path : '/'
},
{
icon: 'file',
label: 'Problem',
path : '/post'
},
{
icon: 'profile',
label: 'Profile',
path : '/mp'
},
{
icon: 'threedot',
label: 'Setting',
path : '/'
}
]
{
icon: 'home',
label: 'Home',
path: '/',
},
{
icon: 'search',
label: 'Search',
path: '/',
},
{
icon: 'file',
label: 'Problem',
path: '/post',
},
{
icon: 'profile',
label: 'Profile',
path: '/mypage',
},
{
icon: 'threedot',
label: 'Setting',
path: '/',
},
];
8 changes: 4 additions & 4 deletions src/components/shared/StyledButton.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import styled from '@emotion/styled';
import { colors } from '@/styles/colorPalette';
import { Colors, colors } from '@/styles/colorPalette';

interface ButtonProp {
width?: string;
background?: string;
color?: string;
color?: Colors;
}

const StyledButton = styled.button<ButtonProp>`
Expand All @@ -14,8 +14,8 @@ const StyledButton = styled.button<ButtonProp>`
display: flex;
justify-content: center;
align-items: center;
background: ${({ background }) => background || colors.yellow};
color: ${({ color }) => color || 'white'};
background: ${({ background = colors.yellow }) => background};
color: ${({ color = 'white' }) => color};
font-size: 20px;
font-weight: 700;
`;
Expand Down
2 changes: 2 additions & 0 deletions src/pages/mypage/profile/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ProfileTable } from '@/components/mypage';
import * as S from './styles';
import { logout } from '@/apis/userapi';

export default function index() {
return (
Expand All @@ -11,6 +12,7 @@ export default function index() {
<ProfileTable />
<S.Block>
<S.Logout>로그아웃</S.Logout>
<button onClick={logout}>logout</button>
</S.Block>
<S.Block>
<S.Title>회원탈퇴</S.Title>
Expand Down

0 comments on commit d2ab0ff

Please sign in to comment.