Cors error
Closed this issue · 1 comments
jangtaehun commented
-
error 내용
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/v1/users/me' from origin 'http://127.0.0.1:3000/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
Django
THIRD_PARTY_APPS = [
"rest_framework",
"rest_framework.authtoken",
"corsheaders",
]
CUSTOM_APPS = [
"common.apps.CommonConfig",
"users.apps.UsersConfig",
"rooms.apps.RoomsConfig",
"experiences.apps.ExperiencesConfig",
"categories.apps.CategoriesConfig",
"reviews.apps.ReviewsConfig",
"wishlists.apps.WishlistsConfig",
"bookings.apps.BookingsConfig",
"medias.apps.MediasConfig",
"direct_messages.apps.DirectMessagesConfig",
]
CORS_ALLOWED_ORIGINS = [
# "http://localhost:3000",
"http://127.0.0.1:3000",
]
CORS_ALLOW_CREDENTIALS = True
- TypeScript
userUser.ts
import { useQuery } from "@tanstack/react-query";
import { getMe } from "../api";
export default function useUser() {
const {isLoading, data, isError} = useQuery<IUser>({queryKey:["me"], queryFn: getMe, retry:false});
return {
userLoading: isLoading,
user: data,
isLoggedIn: !isError,
};
}
api.ts
import { QueryFunctionContext } from "@tanstack/react-query";
import axios from "axios";
const instance = axios.create({
baseURL: "http://127.0.0.1:8000/api/v1/",
withCredentials: true, //api에 요청을 할 때 cookie를 보내겠다 + settings에 추가
})
export const getRooms = () => instance.get("rooms/").then(response => response.data)
export const getRoom = ({queryKey}: QueryFunctionContext) => {
console.log(queryKey)
const [_, roomPk] = queryKey
return instance.get(`rooms/${roomPk}`).then(response => response.data)
// return instance.get(`rooms/${queryKey[1]}`).then(response => response.data)
}
export const getRoomReviews = ({queryKey}: QueryFunctionContext) => {
console.log(queryKey)
const [_, roomPk] = queryKey
return instance.get(`rooms/${roomPk}/reviews`).then(response => response.data)
}
// 사용자 정보 가져오기
export const getMe = () =>
instance.get("users/me").then((response) => response.data);
jangtaehun commented
여러 가지 방법을 찾았다.
- allow cors access-control-allow-origin 설치
- CORS_ORIGIN_ALLOW_ALL = True 추가
외에도 Chat GPT를 통해 더 많은 해결 방법을 찾았지만,
브라우저 캐시 삭제하고 해결.