Skip to content

Commit

Permalink
Feat: SSR의 경우 브라우저의 토큰에 접근할 수 없기 때문에 쿠키에 저장 후 getServerSideProps에서 쿠키…
Browse files Browse the repository at this point in the history
…를 파싱하여 사용(#71)
  • Loading branch information
ohinhyuk committed Oct 31, 2023
1 parent a7206bf commit 8212a03
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 10 deletions.
13 changes: 11 additions & 2 deletions src/pages/mileage/category/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ import { InferGetServerSidePropsType, GetServerSideProps } from 'next';
import MileageCategory from 'src/components/board/MileageCategory';
import { setCategoryList } from 'src/redux/slices/filter';
import { DESCRIPTION1, CATEGORY, DESCRIPTION2, NUM } from '../../../assets/data/fields';
import axios from 'axios';
import { getCookie } from '../view';

interface IList {
id: number;
Expand All @@ -182,8 +184,15 @@ interface IGetMileageCategory {

export const getServerSideProps: GetServerSideProps<{
fetchData: IGetMileageCategory[];
}> = async () => {
// const res = await fetch(`${process.env.NEXT_PUBLIC_HOST_API_KEY}/api/mileage/categories`);
}> = async (context) => {
let { cookie } = context.req.headers;

cookie = cookie ? cookie.split('=')[1] : '';

if (cookie !== '') {
axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${cookie}`;
}

const res = await axiosInstance.get('/api/mileage/categories');
const fetchData = res.data;
console.log(fetchData);
Expand Down
22 changes: 22 additions & 0 deletions src/pages/mileage/view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
REGISTERED_DATE,
} from 'src/assets/data/fields';
import axiosInstance from 'src/utils/axios';
import { useEffect } from 'react';
import axios from 'axios';

/**
* @component [마일리지 조회] 게시판
Expand Down Expand Up @@ -215,7 +217,27 @@ interface Data {
[MileageViewBoard.POINT]: number;
[MileageViewBoard.REGISTERED_DATE]: string;
}
export function setCookie(name, value, days) {
let expires = '';
if (days) {
const date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = '; expires=' + date.toUTCString();
}
document.cookie = name + '=' + (value || '') + expires + '; path=/';
}

export function getCookie(name) {
var value = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return value ? value[2] : null;
}

export default function MileageView() {
setCookie(
'accessToken',
`eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzdHJpbmciLCJhdXRob3JpdGllcyI6IlJPTEVfQURNSU5fRCxST0xFX0FETUlOX0MsUk9MRV9BRE1JTl9CLFJPTEVfQURNSU5fQSIsImV4cCI6MTcwMTUwMjQ4OCwiaWF0IjoxNjk2MzE4NDg4fQ.LnWCsVUPPtrPRtUwOUZgqiCtDCd3j3pbw0G1-Ht1v8Kpl54VVTUmcVzw0dVJnm9iTTJ_ZJzYK1PhqThCMJmRAw`,
7
);

return <EnhancedTable originalRows={rows} headCells={headCells} type="마일리지 조회" />;
}
21 changes: 13 additions & 8 deletions src/utils/axios.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
import axios from 'axios';
import { HOST_API_KEY } from '../config-global';
import { getCookie } from 'src/pages/mileage/view';

const axiosInstance = axios.create({ baseURL: HOST_API_KEY });

axiosInstance.interceptors.request.use((config) => {
if (typeof window !== 'undefined') {
const token = getCookie('accessToken');
// const token = '!!=@';
if (token) {
config.headers.Authorization = `Bearer ${token}`;
// config.withCredentials = true; // withCredentials 옵션 추가
}
}
return config;
});

axiosInstance.interceptors.response.use(
(response) => response,
(error) => {
Expand All @@ -24,12 +37,4 @@ axiosInstance.interceptors.response.use(
}
);

axiosInstance.interceptors.request.use((config) => {
const token = localStorage.getItem('accessToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});

export default axiosInstance;

0 comments on commit 8212a03

Please sign in to comment.