Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat]10주차 과제 완료 #78

Open
wants to merge 2 commits into
base: minho
Choose a base branch
from
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
88 changes: 88 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.4.0",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-cookie": "^4.1.1",
"react-dom": "^18.2.0",
"react-router-dom": "^6.11.1",
"react-scripts": "5.0.1",
Expand Down
5 changes: 4 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import PostEditPage from "./routes/PostEditPage";
import SignUpPage from "./routes/SignUpPage";
import PostDetailPage from "./routes/PostDetailPage";
import SignInPage from "./routes/SignInPage";
import MyPage from "./routes/MyPage";

function App() {
return (
Expand All @@ -26,8 +27,10 @@ function App() {
<Route path="/:postId" element={<PostDetailPage />} />
{/* sign up */}
<Route path="/signup" element={<SignUpPage />} />
{/* sign up */}
{/* sign in */}
<Route path="/signin" element={<SignInPage />} />
{/* my page */}
<Route path="/mypage" element={<MyPage />} />
</Routes>
<Footer />
</BrowserRouter>
Expand Down
170 changes: 170 additions & 0 deletions src/apis/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { instance, instanceWithToken } from "./axios";

// signup and login
export const signIn = async (data) => {
const response = await instance.post("/account/signin/", data);
if (response.status === 200) {
window.location.href = "/";
} else {
console.log("Error");
alert("로그인 실패");
}
};

export const signUp = async (data) => {
const response = await instance.post("/account/signup/", data);
if (response.status === 200) {
window.location.href = "/";
}
return response;
};

//posts
export const getPosts = async () => {
const response = await instance.get("/post/");
console.log(response.data);
return response.data;
};

export const getPost = async (id) => {
const response = await instance.get(`/post/${id}/`);
return response.data;
};

export const createPost = async (data, navigate) => {
const response = await instanceWithToken.post("/post/", data);
if (response.status === 201) {
console.log("POST SUCCESS");
navigate("/");
} else {
console.log("[ERROR] error while creating post");
}
};

export const updatePost = async (id, data, navigate) => {
const response = await instanceWithToken.patch(`/post/${id}/`, data);
if (response.status === 200) {
console.log("POST UPDATE SUCCESS");
navigate(-1);
} else {
console.log("[ERROR] error while updating post");
}
};

// 과제!!
export const deletePost = async (id, navigate) => {
const confirm = window.confirm("정말 삭제하시겠습니까?");
if (!confirm) return;

const response = await instanceWithToken.delete(`/post/${id}/`);
if (response.status === 204) {
console.log("POST DELETE SUCCESS");
navigate(-1);
} else {
console.log("[ERROR] error while deleting post");
}
};

// 과제!!
export const likePost = async (postId) => {
const response = await instanceWithToken.post(`/post/${postId}/like/`);
if (response.status === 201) {
console.log("LIKE SUCCESS");
// window.location.reload();
} else {
console.log("[ERROR] error while liking post");
}
return response;
};

// tags
export const getTags = async () => {
const response = await instance.get("/tag/");
return response.data;
};

export const createTag = async (data) => {
const response = await instanceWithToken.post("/tag/", data);
if (response.status === 201) {
console.log("TAG SUCCESS");
} else {
console.log("[ERROR] error while creating tag");
}
return response; // response 받아서 그 다음 처리
};

// comments
export const getComments = async (postId) => {
const response = await instance.get(`/comment/?post=${postId}`);
return response.data;
};

export const createComment = async (data) => {
const response = await instanceWithToken.post("/comment/", data);
if (response.status === 201) {
console.log("COMMENT SUCCESS");
window.location.reload(); // 새로운 코멘트 생성시 새로고침으로 반영
} else {
console.log("[ERROR] error while creating comment");
}
};

export const updateComment = async (id, data) => {
const response = await instanceWithToken.patch(`/comment/${id}/`, data);
if (response.status === 200) {
console.log("COMMENT UPDATE SUCCESS");
window.location.reload();
} else {
console.log("[ERROR] error while updating comment");
}
};

// 과제 !!
export const deleteComment = async (id) => {
const confirm = window.confirm("정말 삭제하시겠습니까?");
if (!confirm) return;

const response = await instanceWithToken.delete(`/comment/${id}/`);
if (response.status === 204) {
console.log("COMMENT DELETE SUCCESS");
window.location.reload();
} else {
console.log("[ERROR] error while deleting comment");
}
};

export const getUser = async () => {
const response = await instanceWithToken.get(`/account/info/`);
if (response.status === 200) {
// console.log("USER GET SUCCESS");
// // console.log(response.data);
} else {
console.log("[ERROR] error while getting user");
}
return response.data;
};

export const getUserProfile = async (id) => {
const response = await instanceWithToken.get(`/account/info/profile/`);
if (response.status === 200) {
// console.log("USER GET SUCCESS");
// console.log(response.data);
} else {
console.log("[ERROR] error while getting user profile");
}
return response.data;
};

export const updateUserProfile = async (data) => {
const response = await instanceWithToken.patch(
`/account/info/profile/`,
data
);
console.log(response.data, "request로 날린 userProfileInfo");
if (response.status === 200) {
console.log("USER UPDATE SUCCESS");
// window.location.reload();
} else {
console.log("[ERROR] error while updating user");
}
};
52 changes: 52 additions & 0 deletions src/apis/axios.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import axios from "axios";
import { getCookie } from "../utils/cookie";

// baseURL, credential, 헤더 세팅
axios.defaults.baseURL = "http://localhost:8000/api";
axios.defaults.withCredentials = true;
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.common["X-CSRFToken"] = getCookie("csrftoken");

// 누구나 접근 가능한 API들
export const instance = axios.create();

// Token 있어야 접근 가능한 API들 - 얘는 토큰을 넣어줘야 해요
export const instanceWithToken = axios.create();

// instanceWithToken에는 쿠키에서 토큰을 찾고 담아줍시다!
instanceWithToken.interceptors.request.use(
// 요청을 보내기전 수행할 일
// 사실상 이번 세미나에 사용할 부분은 이거밖에 없어요
(config) => {
const accessToken = getCookie("access_token");

if (!accessToken) {
// token 없으면 리턴
return;
} else {
// token 있으면 헤더에 담아주기 (Authorization은 장고에서 JWT 토큰을 인식하는 헤더 key)
config.headers["Authorization"] = `Bearer ${accessToken}`;
}
return config;
},

// 클라이언트 요청 오류 났을 때 처리
(error) => {
// 콘솔에 찍어주고, 요청을 보내지 않고 오류를 발생시킴
console.log("Request Error!!");
return Promise.reject(error);
}
);

instanceWithToken.interceptors.response.use(
(response) => {
// 서버 응답 데이터를 프론트에 넘겨주기 전 수행할 일
console.log("Interceptor Response!!");
return response;
},
(error) => {
// 서버가 오류를 응답했을 때 처리 - 콘솔 찍어주고, 프론트에게 보내지 않고 오류를 발생시킴
console.log("Response Error!!");
return Promise.reject(error);
}
);
Loading