Skip to content

Commit

Permalink
Merge pull request #26 from 14-team13/11-feature-axios-instance
Browse files Browse the repository at this point in the history
11 feature axios instance
  • Loading branch information
nickkies authored Mar 15, 2023
2 parents 783d330 + 8dfb3e5 commit 0fc1a2a
Show file tree
Hide file tree
Showing 7 changed files with 134 additions and 16 deletions.
1 change: 1 addition & 0 deletions host/config-overrides.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ module.exports = function (config, env) {
"@layouts": path.resolve(__dirname, "src/layouts"),
"@hooks": path.resolve(__dirname, "src/hooks"),
"@utils": path.resolve(__dirname, "src/utils"),
"@api": path.resolve(__dirname, "src/api")
}),
)(config, env)
);
Expand Down
41 changes: 41 additions & 0 deletions host/src/api/core/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import axios from "axios";

const request = axios.create({
baseURL: "http://localhost:8123"
})

//요청 타임아웃 설정
request.defaults.timeout = 2500;
request.defaults.withCredentials = true;
// request.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;

//요청 인터셉터 추가
request.interceptors.request.use(
config => { //요청을 보내기 전에 수행할 로직
return config
},
error => {
//요청 에러가 발생했을 때 수행할 로직
console.log(error); //디버깅
return Promise.reject(error);
}
);

//응답 인터셉터 추가
request.interceptors.response.use(
response => {
//응답에 대한 로직 작성
//const res = response.data
//return res
return response
},

error => {
//응답 에러가 발생했을 때 수행할 로직
console.log(error); //디버깅
return Promise.reject(error);
}
);


export default request; //axios 인스턴스를 내보낸다.
30 changes: 30 additions & 0 deletions host/src/api/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import request from "./core";


export const login = (email: string, password: string) => {
return request(
{
method: 'POST',
url: '/login',
data: {
email: email,
password: password
}
}
)
}

export const loginsuccess = () => {
return request({
// method: 'GET',
url: '/login/success'
});
}

export const logout = () => {
return request({
method: 'POST',
url: '/logout'
});
}

3 changes: 3 additions & 0 deletions host/src/bootstrap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "./index.css";
import { BrowserRouter } from "react-router-dom";
import axios from "axios";
axios.defaults.baseURL = "http://localhost:8123"; // 임시 서버
axios.defaults.withCredentials = true;

const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
Expand Down
23 changes: 12 additions & 11 deletions host/src/pages/LogIn/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,23 @@ import fetcher from '@utils/fetcher';
import axios from 'axios';
import React, { useCallback, useState } from 'react';
import useSWR from 'swr';
import { login } from "@api/main"

const LogIn = () => {
const { data: userData, error, mutate } = useSWR('/api/users', fetcher);
// const { data: userData, error, mutate } = useSWR('/api/users', fetcher);
const [logInError, setLogInError] = useState(false);
const [email, onChangeEmail] = useInput('');
const [password, onChangePassword] = useInput('');
const onSubmit = useCallback( (e) => {
e.preventDefault();
setLogInError(false);
axios.post('/api/users/login',{ email, password },{ withCredentials: true})
.then(() => { mutate();})
.catch((error) => {
setLogInError(error.response?.data?.code === 401);
});
},
[email, password, mutate],

const onSubmit = useCallback(async (e) => {
e.preventDefault();
setLogInError(false);
const response = await login(email, password)
if (response.status === 200) {
window.open('/', '_self')
}
},
[email, password],
);

return (
Expand Down
51 changes: 46 additions & 5 deletions host/src/pages/Main/index.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,66 @@
import React from 'react';
import { useEffect, useState } from "react";
import axios from "axios";
import { useRecoilState } from 'recoil';
import { userState } from "../../store/atoms";
import { loginsuccess, logout } from "@api/main"

const Main = () => {
const [isLogin, setIsLogin] = useState(false);
const [user, setUser] = useRecoilState(userState);

const Menu = React.lazy(() =>
// @ts-ignore
import("remote/Menu").then((module) => {return {default: module.Menu};
import("remote/Menu").then((module) => {
return { default: module.Menu };
})
);

useEffect(() => {
(async () => {
const { data } = await loginsuccess();
try {
if (data) {
setIsLogin(true);
setUser({ email: data.email, username: data.username });
}
} catch (error) {
console.log(error);
}
})();
}, []);


const logoutPage = async () => {
const data = await logout();
if (data.status === 200) {
window.open("/login", "_self");
}

};

return (
<div className="App">
<div> 여기가 Host </div>
<div> AOCE </div>
<div>
<a href="/signup">회원가입</a>
<a href="/login">로그인</a>
{/* <p>Name: {user.email}</p>
<p>Age: {user.username}</p> */}
<div>
{isLogin && <div>
<button onClick={logoutPage} className="loginButton">
Logout
</button>
</div>}
{!isLogin &&
<div>
<a href="/signup">회원가입</a>
<a href="/login">로그인</a>
</div>
}
</div>
<div>
<React.Suspense fallback={<div>Loading...</div>}>
<Menu/>
<Menu />
</React.Suspense>
</div>
</div>
Expand Down
1 change: 1 addition & 0 deletions host/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@pages/*": ["pages/*"],
"@utils/*": ["utils/*"],
"@hooks/*": ["hooks/*"],
"@api/*": ["api/*"]
}
},
"include": [
Expand Down

0 comments on commit 0fc1a2a

Please sign in to comment.