Skip to content

Commit

Permalink
Merge pull request #53 from leejaeseong11/fix-axios
Browse files Browse the repository at this point in the history
Fix : axios-interceptor 적용
  • Loading branch information
KANU896 authored Dec 15, 2023
2 parents 6d0038a + 28c7e75 commit 06715d4
Show file tree
Hide file tree
Showing 14 changed files with 149 additions and 57 deletions.
83 changes: 83 additions & 0 deletions src/axios-interceptor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import axios from "axios"

var apiClient = null;
apiClient = axios.create({
// baseURL: "//" + "192.168.1.116:8881/codesparring",
baseURL: import.meta.env.VITE_BACK_URL,
withCredentials: true
});

apiClient.interceptors.request.use(
function (config) {
config.headers["Content-Type"] = "application/json;";
config.headers["Authorization"] = `Bearer ${sessionStorage.getItem('accessToken')}`;
return config;
}
)

apiClient.interceptors.response.use(res => {
if (!(res.status === 200 || res.status === 201 || res.status === 204)) throw new Error();
if (res.data.errors) throw new Error(res.data.errors);

return res;
}

,async (error) => {
if (error.response?.status === 401) {
alert("로그인이 필요합니다")
window.location.href='/login';
}
if (error.response?.status === 403 || error.response?.status === 500) {
console.error("403 Forbidden 에러 발생 :", error.response)
alert("접근 권한이 없습니다")
window.history.back();
}
return Promise.reject(error);
}

// ,async (error) => {
// const err = error;
// console.log("==================//response================");
// console.log(error);
// console.log("==================response//================");
// if (err.response?.status === 401) {
// const data = err.response?.data;
// console.log(err.response);
// console.log("data====");
// console.log(data);

// //if (토큰 재발행) {
// const param = {
// 'refreshToken' : '',
// 'accessToken':`Bearer ${sessionStorage.getItem('accessToken')}`
// }

// console.log(param);
// // const token = await axios.get('http://127.0.0.1:8881/codesparring/auth/reissue?refreshToken='+param.refreshToken + "&accessToken="+param.accessToken, {
// // headers: {
// // "Content-Type" : "application/json"
// // }
// // });
// const token = await axios.post('http://127.0.0.1:8881/codesparring/auth/reissue', param,{
// headers: {
// "Content-Type" : "application/json"
// }
// });
// console.log("token=======");
// console.log(token);
// sessionStorage.setItem("accessToken", token);
// err.config.headers = {
// "Content-Type": "application/json",
// Authorization: `Bearer ${token}`,
// };
// // 중단된 요청을 새로운 토큰으로 재전송
// const originalResponse = await axios.request(err.config);
// return originalResponse.data;
// // }
// }

// return Promise.reject(error);
// }
);

export {apiClient};
14 changes: 8 additions & 6 deletions src/components/admin/adminQuizPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@
</main>
</template>
<script>
import axios from 'axios'
// import axios from 'axios'
import {apiClient} from '@/axios-interceptor'
import AdminQuizPopup from '../quiz/AdminQuizPopup.vue'
export default {
Expand Down Expand Up @@ -124,8 +125,8 @@ export default {
this.currentPage = this.$route.params.currentPage
const url = `${this.backURL}/quiz/list/${this.currentPage}`
axios
const url = `${this.backURL}/admin/quiz/list/${this.currentPage}`
apiClient
.get(url)
.then((res) => {
this.quizList = res.data.list
Expand All @@ -134,7 +135,8 @@ export default {
this.totalPage=res.data.totalPage
})
.catch(() => {
alert('관리자 페이지를 조회할 수 없습니다')
// alert('관리자 페이지를 조회할 수 없습니다')
console.error('Error fetching reports:', error.message);
})
} else if (filter == 'UNRANKED') {
const onBt = document.getElementById('quiz-urk')
Expand All @@ -149,8 +151,8 @@ export default {
this.currentPage = this.$route.params.currentPage
const url = `${this.backURL}/quiz/tier/UNRANKED/${this.currentPage}`
axios
const url = `${this.backURL}/admin/quiz/tier/UNRANKED/${this.currentPage}`
apiClient
.get(url)
.then((res) => {
this.quizList = res.data.list
Expand Down
39 changes: 20 additions & 19 deletions src/components/admin/adminReportPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
<div v-for="report in reportList" :key="report.reportNo" class="report-object">
<span class="report-no">{{ report.reportNo }}</span>
<span class="report-Type">{{ formatReportType(report.reportType) }}</span>
<span class="report-Date">{{ formatDate(report.reportDate) }}</span>
<span class="report-Date">{{ report.reportDate }}</span>
<!-- <span class="report-Date">{{ formatDate(report.reportDate) }}</span> -->
<span class="report-memberName">{{ report.memberName }}</span>
<button class="report-info-bt" :id="'' + report.reportNo" @click="reportView">조회</button>
</div>
Expand All @@ -40,7 +41,8 @@
</main>
</template>
<script>
import axios from 'axios'
// import axios from 'axios'
import {apiClient} from '@/axios-interceptor'
export default {
name: 'AdminReportPage',
data() {
Expand All @@ -67,20 +69,19 @@ export default {
text.value = ''
this.currentPage = this.$route.params.currentPage
const url = `${this.backURL}/report/date?page=${this.currentPage - 1}`
axios
const url = `${this.backURL}/admin/report/all?page=${this.currentPage - 1}`
apiClient
.get(url)
.then((res) => {
console.log(res.data)
this.reportList = res.data.content
this.totalPage = res.data.totalPages
alert(this.totalPage)
this.startPage = Math.floor((this.currentPage - 1) / 5) * 5 + 1;
this.endPage = Math.ceil(res.data.totalElements / 10);
})
.catch((error) => {
console.error('Error fetching reports:', error.message);
alert('신고목록을 조회할 수 없습니다')
// alert('신고목록을 조회할 수 없습니다')
})
} else if (filter == 'UNRANKED') {
const onBt = document.getElementById('report-urk')
Expand All @@ -94,8 +95,8 @@ export default {
text.value = ''
this.currentPage = this.$route.params.currentPage
const url = `${this.backURL}/report/commentNull?page=${this.currentPage - 1}`
axios
const url = `${this.backURL}/admin/report/commentNull?page=${this.currentPage - 1}`
apiClient
.get(url)
.then((res) => {
this.reportList = res.data.content
Expand All @@ -111,7 +112,7 @@ export default {
},
methods: {
allReport() {
location.href = '/admin/report/date/1'
location.href = '/admin/report/all/1'
},
urkReport() {
location.href = '/admin/report/UNRANKED/1'
Expand Down Expand Up @@ -151,18 +152,18 @@ export default {
},
quizView(e) {
location.href = '/report/' + e.target.id
location.href = '/admin/report/' + e.target.id
},
formatDate(reportDate) {
const date = new Date(reportDate);
const formattedDate = date.toLocaleDateString('ko-KR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
return formattedDate;
},
// formatDate(reportDate) {
// const date = new Date(reportDate);
// const formattedDate = date.toLocaleDateString('ko-KR', {
// year: 'numeric',
// month: '2-digit',
// day: '2-digit',
// });
// return formattedDate;
// },
formatReportType(reportType) {
switch (reportType) {
case 1:
Expand Down
5 changes: 3 additions & 2 deletions src/components/home/MainHomeRoom.vue
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@
</div>
</template>
<script>
import axios from 'axios'
// import axios from 'axios'
import {apiClient} from '@/axios-interceptor'
import ShowQuizSimply from './ShowQuizSimply.vue'
import sweetAlert from '../../util/modal.js'
Expand All @@ -87,7 +88,7 @@ export default {
} else {
addMemberUrl = `${this.backURL}/room-member`
}
axios
apiClient
.post(addMemberUrl, {})
.then((response) => {
console.log(response)
Expand Down
8 changes: 4 additions & 4 deletions src/components/profile/RankHistory.vue
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
</div>
</template>
<script>
import axios from 'axios'
// import axios from 'axios'
import {apiClient} from '@/axios-interceptor'
export default {
name: 'RankHistory',
data() {
Expand Down Expand Up @@ -60,7 +60,7 @@ export default {
handleScrollEnd() {
this.currentPage++
const url = `${this.backURL}/rankgame/` + this.memberNo + `/` + this.currentPage
axios.get(url).then((res) => {
apiClient.get(url).then((res) => {
this.tmpList = res.data.list
this.rankList.push(...this.tmpList)
this.tmpList = []
Expand All @@ -71,7 +71,7 @@ export default {
this.memberNo = this.$route.params.memberNo
const url = `${this.backURL}/rankgame/` + this.memberNo + `/` + this.currentPage
axios.get(url).then((res) => {
apiClient.get(url).then((res) => {
this.rankList = res.data.list
this.memberName = res.data.list[0].memberName
this.memberTier = res.data.list[0].myTier
Expand Down
5 changes: 3 additions & 2 deletions src/components/quiz/AddTestcase.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
</div>
</template>
<script>
import axios from 'axios'
// import axios from 'axios'
import {apiClient} from '@/axios-interceptor'
export default {
name: 'AddTestcase',
Expand All @@ -32,7 +33,7 @@ export default {
testcaseInput: this.inputValue,
testcaseOutput: this.outputValue
}
axios
apiClient
.post(url, JSON.stringify(data), {
headers: {
'Content-Type': 'application/json'
Expand Down
6 changes: 3 additions & 3 deletions src/components/quiz/AdminQuizPopup.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
</div>
</template>
<script>
import axios from 'axios'
// import axios from 'axios'
import {apiClient} from '@/axios-interceptor'
export default {
name: 'AdminQuizPopup',
data() {
Expand All @@ -32,7 +32,7 @@ export default {
created() {
const quizNo=document.getElementById('search-text').value
const url = `${this.backURL}/quiz/${quizNo}`
axios.get(url).then((res) => {
apiClient.get(url).then((res) => {
this.quizNo=res.data.quizNo
this.quizTitle=res.data.quizTitle
this.quizAuthor=res.data.memberName
Expand Down
5 changes: 3 additions & 2 deletions src/views/code/CodeView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@
</main>
</template>
<script>
import axios from 'axios'
// import axios from 'axios'
import {apiClient} from '@/axios-interceptor'
export default {
name: 'CodeView',
Expand Down Expand Up @@ -156,7 +157,7 @@ export default {
created() {
this.quizNo = this.$route.params.quizNo
const url = `${this.backURL}/quiz/${this.quizNo}`
axios
apiClient
.get(url)
.then((res) => {
this.quizTitle = res.data.quizTitle
Expand Down
9 changes: 5 additions & 4 deletions src/views/home/MainHome.vue
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@
</div>
</template>
<script>
import axios from 'axios'
// import axios from 'axios'
import {apiClient} from '@/axios-interceptor'
import MainHomeRoom from '../../components/home/MainHomeRoom.vue'
import MemberProfile from '../../components/home/MemberProfile.vue'
import AddRoom from '../../components/room/AddRoom.vue'
Expand Down Expand Up @@ -229,7 +230,7 @@ export default {
methods: {
refreshButtonClickHandler() {
this.inputRoomNo = null
axios
apiClient
.get(`${this.backURL}/room?page=${this.roomPage}&size=${this.roomSize}`)
.then((response) => {
this.roomList = response.data.content
Expand Down Expand Up @@ -275,7 +276,7 @@ export default {
logoutButtonClickHandler() {
console.log('Request sent')
const url = `${this.backURL}/auth/logout`
axios
apiClient
.post(
url,
{},
Expand Down Expand Up @@ -315,7 +316,7 @@ export default {
if (this.inputRoomNo == null) {
this.refreshButtonClickHandler()
} else {
axios
apiClient
.get(
`${this.backURL}/room?searchNo=${this.inputRoomNo}&page=${this.roomPage}&size=${this.roomSize}`
)
Expand Down
1 change: 0 additions & 1 deletion src/views/member/Login.vue
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ export default {
.catch(error => {
console.error('Error:', error);
});
alert("end loginFormSubmitHandler")
}
},
Expand Down
Loading

0 comments on commit 06715d4

Please sign in to comment.